我正在编写一个发送确认电子邮件的servlet。
通常情况下,它工作正常,但是如果我快速调用它几次(延迟时间<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);
}
});
}
}
答案 0 :(得分:1)
尝试在初始化期间设置属性connectiontimeout和timeout
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);
}
});
}
}