I'm trying to get this example for the Apache Commons email library to work. Here is my code:
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("username@gmail.com", "password"));
email.setTLS(true);
try {
email.setFrom("username@gmail.com");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("username@gmail.com");
System.out.println("Sending...");
email.send();
System.out.println("Email sent!");
} catch (Exception e) {
System.out.println("Email not sent!");
e.printStackTrace();
}
As you can see it's basically unchanged from the example, except I have to use port 465 instead of 587 because 587 causes a Connection refused
exception (based on this question ). Now this code is hanging on the email.send()
line. The only output I get is:
Sending...
But no exceptions are thrown. Do I need to open a port in my firewall? (I might not be able to do that as I'm trying to do this from work). Thanks!
After a long time I get this exception:
org.apache.commons.mail.EmailException: Sending the email to the following server failed : smtp.gmail.com:465
...
Caused by: javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1
根据您的编辑和对我的评论的回答,您不应在Java代码中查找问题,而应在防火墙或网络配置中查找问题。
You need to set the following (because you are using SSL)
Properties props = new Properties();
props.put("mail.smtp.auth", true);
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.timeout" , "10000");
props.put("mail.smtp.connectiontimeout" , "10000");
props.put("mail.smtp.socketFactory.port", 465);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.