要求:
- 只允许 1 个与邮件服务器的连接(来 self 的客户的限制)
- 发送邮件后不要关闭连接,通过现有连接重新发送邮件(每封邮件都不需要transport.connect(),因此性能更好)
- 通过该连接发送所有邮件
- 如果连接失败,重新连接,发送邮件
- Java 1.6
我的代码运行良好,但有时我会收到 javax.mail.MessagingException
,错误代码为 250:来自 SMTP 主机的问候语不好
。
嵌套异常是java.net.SocketException:Socket已关闭
:
这是我的客户端代码,该行已标记,其中抛出异常:
// the mail service is a singleton and has one property to store the transport
// object that gets initialized when the singleton instance gets created:
private Transport transport = null;
// props, authU, authP and msg are all passed as a parameter to the sending method:
if (transport == null) {
Session session = Session.getInstance(props, null);
transport = session.getTransport("smtp");
}
if(!transport.isConnected()) {
transport.connect(authU, authP); // <<<<< This line throws the exception !
}
transport.sendMessage(msg, msg.getAllRecipients());
显然,transport.isConnected()
检测到没有连接,但 connection() 不会重新打开或重新创建套接字。我的假设是它会为我做所有必要的事情。
是否有适当的客户端解决方案来确保不会抛出异常? 解决方法是捕获异常并重新发送邮件,但我不喜欢解决方法...
最佳答案
您所描述的解决方法实际上是正确的方法。
在调用 isConnected 方法和调用 sendMessage 方法之间,没有什么可以阻止服务器断开连接,因此在最坏的情况下,您始终必须做好处理异常的准备。
关于Java邮件 : MessagingException: Got bad greeting from SMTP host — Error Code 250,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17520875/