2

要求
- 只允许 1 个与邮件服务器的连接(来自我的客户的限制) -发送邮件后不要关闭连接
,通过现有连接重新发送邮件(更好的性能,因为每个邮件都不需要 transport.connect()) - 发送该连接上的所有邮件
- 如果连接失败,请重新连接,发送邮件
- Java 1.6

我的代码运行良好,但有时我得到javax.mail.MessagingException错误代码250: Got bad greeting from SMTP host。嵌套异常是:java.net.SocketException: Socket closed

这是我的客户端代码,该行已标记,引发异常:

// 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() 没有重新打开或重新创建套接字。我的假设是它会为我做所有必要的事情。

是否有适当的客户端解决方案来确保不会引发异常?一种解决方法是捕获异常并重新发送邮件,但我不喜欢解决方法......

4

2 回答 2

2

您所描述的解决方法实际上是正确的方法。

没有什么可以阻止服务器在您调用 isConnected 方法和调用 sendMessage 方法之间断开连接,因此在最坏的情况下,您始终必须准备好处理异常。

于 2013-07-08T22:02:31.467 回答
0

试试这个解决方案:

public static void mail(Reporter report) {
    
 
        if(!sendEmail.trim().equalsIgnoreCase("true")){
            return;
        }
        
 
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.port", "587");
 
        Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });
 
        try {     
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("from-email@gmail.com"));
            if(!bccEmail.trim().isEmpty()){
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(bccEmail));
            }
            message.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(toEmail));
            message.setSubject(" Testing ");
            message.setText("automatic email  ,"+report);
            Transport.send(message);
 
            System.out.println("Email Done");
 
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
于 2013-07-08T07:14:00.783 回答