通过gmail从java发送电子邮件的例外情况

时间:2014-12-04 09:02:34

标签: java email ssl smtp

尝试通过gmail从java发送电子邮件时,我收到以下异常。

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1391)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:412)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at Mail.Send(Mail.java:75)
at Mail.main(Mail.java:85)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.security.ssl.SSLSocketImpl.connect(Unknown Source)
at sun.security.ssl.BaseSSLSocketImpl.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:233)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1359)
... 5 more

我提到了http://www.tutorialspoint.com/javamail_api/javamail_api_gmail_smtp_server.htmSend email using java,但SSL和TLS都会遇到同样的异常。对此有何解决方法?

提前致谢。

2 个答案:

答案 0 :(得分:0)

您需要在GMAIL中启用SMTP访问,同时您还需要为您的帐户启用不安全的客户端:

https://www.google.com/settings/security/lesssecureapps

https://support.google.com/mail/answer/75726

请注意,您要使用的smtp端口已在防火墙中打开!我建议尝试使用Thunderbird运行代码的机器进行连接检查。然后你知道客户端是否能够连接。

答案 1 :(得分:0)

在GMAIL中启用SMTP访问后,您还需要为您的帐户允许不安全的客户端(由LucasF建议) 试试这个配置:

host :smtp.gmail.com
port :587
username :you@gmail.com
password :yourpassword
   JavaMailProperties : 
     mail.transport.protocol : smtp
     mail.smtp.auth : true
     mail.smtp.starttls.enable :true
     mail.debug :true

我使用导入org.springframework.mail.SimpleMailMessage类来使用此配置,它可以正常工作。