Java错误javax.mail.MessagingException:无法连接到SMTP主机:

时间:2012-03-15 13:12:18

标签: java javamail

我有一个发送电子邮件的java应用程序。它一直运行良好从未遇到过此问题。突然间,今天我看到了很多这样的错误,但也有一些成功通过.Below是完整的痕迹。

javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
java.net.ConnectException: Connection timed out
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
javax.mail.Service.connect(Service.java:317)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at commServer9000$MailProcessor.run(commServer9000.java:6550)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.net.ConnectException: Connection timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
    ... 8 more

1 个答案:

答案 0 :(得分:0)

在这种情况下,启用SSL解决了我的问题。

JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setHost("smtp.gmail.com");
mailSender.setPort(465);

//setting username and password
mailSender.setUsername("UserName");
mailSender.setPassword("Password");

//setting Spring JavaMailSenderImpl Properties
Properties mailProp = mailSender.getJavaMailProperties();

mailProp.put("mail.transport.protocol", "smtp");
mailProp.put("mail.smtp.auth", "true");
mailProp.put("mail.smtp.starttls.enable", "true");
mailProp.put("mail.smtp.starttls.required", "true");
mailProp.put("mail.debug", "true");
mailProp.put("mail.smtp.ssl.enable", "true");
mailProp.put("mail.smtp.user", String.valueOf(resourceList.get(0)));