2013-12-10 59 views
1

我在寫一個發送確認電子郵件的servlet。Java.mail超時時調用

一般來說,它工作正常,但如果我快速調用它幾次(延遲爲< 1秒),它將掛起Transport.send開始失敗,或者它引發錯誤「無法連接到SMTP主機:mail。[domain] .org,port:25「,堆棧跟蹤解釋超時。我最初認爲這是一個線程問題,但即使我只是在它們之間短暫延遲的線程上調用呼叫,它也會發生。我爲郵件服務器使用了一個已建立的ISP,因此它似乎應該能夠處理超過1個請求/秒。有誰知道如何解決這個問題?

private void sendConfirmationEmail (String email, String invitationID){ 

    log.info("sendConfirmationEmail called"); 

    String body = "Sample email sent to " + email; 

    initSession(); 

    try { 

     MimeMessage message = new MimeMessage(mySession); 
     message.setFrom(new InternetAddress(FROM, "Test account")); 

     message.addRecipient(Message.RecipientType.TO, new InternetAddress(email)); 
     message.setSubject(SUBJECT); 
     message.setText(body); 

     log.info("about to send over transport for " + email); 
     Transport.send(message); 
     log.info("Email sent"); 

    } 
    catch (MessagingException e) { 
     log.log(Level.SEVERE, "Could not send confirmation email: " + e.getMessage()); 
    } 
    catch (java.io.UnsupportedEncodingException e){ 
     log.log(Level.WARNING, "Unsupported Encoding"); 
    } 
} 

我初始化會話使用此代碼靜態變量:

public static void initSession() { 
    if (mySession == null){ 

     Properties props = new Properties(); 
     props.put("mail.smtp.host", HOST); 
     props.put("mail.smtp.auth", "true"); 

     mySession = Session.getDefaultInstance(props, new javax.mail.Authenticator(){ 
       protected PasswordAuthentication getPasswordAuthentication() { 
        return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD); 
       } 
      }); 

    } 
} 
+1

這是極過程中設置該屬性connectiontimeout和超時可能是導致問題的服務器。我不得不相信,任何值得重量的郵件服務器都會阻止客戶反覆淹沒請求。 – CodeChimp

+0

是的,事實證明,服務器正在用戶之間共享並在某個點後排隊請求,但即使消息得到了適當的接收,調用仍然超時。 – Toby

回答

1

嘗試初始化

public static void initSession() { 
    if (mySession == null){ 

    Properties props = new Properties(); 
    props.put("mail.smtp.host", HOST); 
    props.put("mail.smtp.auth", "true"); 
    props.put("mail.smtp.connectiontimeout", 1200); 
    props.put("mail.smtp.timeout", 1000); 

    mySession = Session.getDefaultInstance(props, new javax.mail.Authenticator(){ 
      protected PasswordAuthentication getPasswordAuthentication() { 
       return new PasswordAuthentication(SMTP_USERNAME, SMTP_PASSWORD); 
      } 
     }); 

} 

}