【问题标题】:JAVA Mail and Office 365 hanging upon connectionJAVA Mail 和 Office 365 在连接时挂起
【发布时间】:2018-06-11 13:36:11
【问题描述】:

我们有一个应用程序严重依赖 JAVA Mail 来发送电子邮件。我们已经按照以下设置了连接超时属性(从 Long 值设置,是否需要整数才能生效?):

props.put("mail.smtp.timeout",           1000L);
props.put("mail.smtp.connectiontimeout", 1000L);

一段时间后,应用程序停止并且永远无法从 Office 365 smtp 帐户恢复(仅在 Office 365 中发生)。我们在 JAVA 邮件中启用了调试模式,它失败的行如下:

DEBUG: setDebug: JavaMail version 1.4.5
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp-mail.outlook.com", port 587, isSSL false

当达到这一点时,套接字超时似乎不起作用,应用程序停止。下面是一个无限循环,不断连接到邮件服务器,然后最终卡住。

public static void main(String[] args){
    String smtpServer   = "smtp-mail.outlook.com";
    String username     = "test@domain.com";
    String password     = "password";
    int portNumber      = 587;
    Long socketTimeout  = 10000L;

    Properties props = new Properties();
    props.put("mail.smtp.ssl.trust",            "*");
    props.put("mail.smtp.host",                 "smtp-mail.outlook.com");
    props.put("mail.smtp.auth",                 "true");
    props.put("mail.smtp.port",                 portNumber);
    props.put("mail.smtp.timeout",              socketTimeout);
    props.put("mail.smtp.connectiontimeout",    socketTimeout);
    props.put("mail.smtp.starttls.enable",      "true");

    Authenticator authenticator = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    };

    while(true){
        Session sess = Session.getInstance(props, authenticator);
        sess.setDebug(true);

        try {
            Transport t = sess.getTransport("smtp");
            t.connect(smtpServer, portNumber, username, password);
            t.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

    标签: java office365 jakarta-mail


    【解决方案1】:

    如果你阅读documentation,上面写着:

    SMTP 协议提供程序支持以下属性,其中 可以在 JavaMail Session 对象中设置。属性总是 设置为字符串;类型列描述了字符串是怎样的 解释。例如,使用

        props.put("mail.smtp.port", "888");
    

    设置 mail.smtp.port 属性,该属性为 int 类型。

    这些属性实际上应该是字符串,但较新版本的 JavaMail 也会接受它们作为整数,而不是长整数。

    另外,请注意您可以get rid of your Authenticator,因为您将用户名和密码直接传递给 connect 方法。而且您不需要为主机和端口设置属性,因为您也直接传递它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2021-03-31
      相关资源
      最近更新 更多