解决问题:javax.mail.MessagingException: Could not connect to SMTP host: smtp.exmail.qq.com, port: 25;

时间:2022-03-17 15:33:21

最近项目中需要用到发送邮件这一功能,总是遇到这样的一个报错:

javax.mail.MessagingException: Could not connect to SMTP host: smtp.exmail.qq.com, port: 25;
  nested exception is:
java.net.ConnectException: Connection timed out: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at 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:253)
at javax.mail.Transport.send(Transport.java:124)
at io.batcloud.util.SendMail.send(SendMail.java:150)
at io.batcloud.util.MessageSentTool.sent(MessageSentTool.java:80)
at io.batcloud.task.SentEmailByThread.dotask(SentEmailByThread.java:59)
at io.batcloud.task.SentEmailByThread.run(SentEmailByThread.java:36)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:299)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:234)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
... 11 more


因为需要发送多个邮箱,比如一个邮件任务里,需要发送把同一个内容发送到几十个或者更多的邮件,为了做到群发单显,所以不能一次性把所有人都写在收件人那里,这样会暴露其他收件的邮箱地址,于是只能一个循环地发送。但是发了第一第二个之后,从第三个开始,总是会有这样的报错发生。


奉劝各位一句,不要用Transport.send(message);这个静态方法来发送邮件。因为这个方法会连接服务器,然后发送邮件,然后关闭邮件服务器,如果发送的邮件多了,就会重复同样的动作,导致报以上的错误。这样可能会邮件服务器那边拒绝掉。尤其是公共的那些邮件服务器。


后来,我改用我在发送的时候使用

transport = session.getTransport();

transport.connect();

然后发送邮件

transport.sendMessage(message, message.getAllRecipients());


等判断所有邮件都发送完毕了,再


transport.close();


这样就可以顺利发送多个邮件了。