簡體   English   中英

連接時掛起JAVA Mail和Office 365

[英]JAVA Mail and Office 365 hanging upon connection

我們有一個非常依賴JAVA Mail來發送電子郵件的應用程序。 我們已按照如下設置了連接超時屬性(從Long值中設置,要使此值生效,是否需要Integer?):

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();
        }
    }
}

如果您閱讀文檔 ,其中說:

SMTP協議提供程序支持以下屬性,可以在JavaMail Session對象中設置這些屬性。 這些屬性始終設置為字符串。 “類型”列描述了如何解釋字符串。 例如使用

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

設置類型為int的mail.smtp.port屬性。

這些屬性實際上應該是Strings,但是較新版本的JavaMail也會將它們接受為Integers,但不能接受Longs。

另外,請注意,由於您將用戶名和密碼直接傳遞給connect方法,因此可以擺脫Authenticator的困擾。 而且,您無需直接為主機和端口設置屬性,因為它們也直接傳遞給它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM