Java邮件 : MessagingException: Got bad greeting from SMTP host — Error Code 250

标签 java sockets email jakarta-mail

要求:
- 只允许 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/

相关文章:

java - 如何在点击选项卡时显示Toast消息?

java - 进程运行时在窗口中显示计时器

macos - SCTP 在 OSX 上缺少包含文件?

php - 为什么我应该使用 MailChimp 或类似的而不是定制的脚本?

java - 使用链表上的递归进行快速排序

java - 解析游标输出java

c# - 一次发送大量数据包时,异步套接字始终读取 0 字节

java - 在 Scala 中与服务器的类似 Telnet 的连接

python - 在 python 2.X 中混合 unicode 和 str ...问题?

python - 像 PHP 一样用 Python 发送电子邮件