挂在 send() 上的共享电子邮件示例
我正在尝试让 此示例 使 Apache Commons 电子邮件库正常工作。这是我的代码:
SimpleEmail email = new SimpleEmail();
email.setHostName("smtp.gmail.com");
email.setSmtpPort(465);
email.setAuthenticator(new DefaultAuthenticator("[email protected]", "password"));
email.setTLS(true);
try {
email.setFrom("[email protected]");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("[email protected]");
System.out.println("Sending...");
email.send();
System.out.println("Email sent!");
} catch (Exception e) {
System.out.println("Email not sent!");
e.printStackTrace();
}
正如您所看到的,它与示例基本没有变化,只是我必须使用端口 465 而不是 587,因为 587 会导致 Connection returned
异常(基于 这个问题)。现在这段代码挂在 email.send()
行上。我得到的唯一输出是:
Sending...
但没有抛出异常。我需要在防火墙中打开端口吗? (我可能无法做到这一点,因为我正试图在工作中做到这一点)。谢谢!
编辑
很长一段时间后我得到了这个异常:
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
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("[email protected]", "password"));
email.setTLS(true);
try {
email.setFrom("[email protected]");
email.setSubject("TestMail");
email.setMsg("This is a test mail ... :-)");
email.addTo("[email protected]");
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!
Edit
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
根据您的编辑和对我的评论的回答,您不应该在 Java 代码中查找问题,而应该在防火墙或网络配置中查找问题。
Based on your edits and answer to my comment, you shouldn't look for your problems in Java code, but in the firewall or your network configuration.
您需要设置以下内容(因为您使用的是 SSL)
You need to set the following (because you are using SSL)