Java.mail 调用过于频繁时超时

标签 java email servlets

我正在编写一个发送确认电子邮件的 servlet。

一般来说,它工作正常,但如果我快速调用它几次(延迟<1秒),它就会开始失败,卡在 Transport.send 上,或者抛出错误“无法连接到 SMTP 主机:mail.[domain].org,端口: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");
    }
}

我使用以下代码将 session 初始化为静态变量:

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

    }
}

最佳答案

尝试设置属性connectiontimeout和初始化期间的超时

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

}

}

关于Java.mail 调用过于频繁时超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20504835/

相关文章:

javascript - 有序的 JSONObject

java - 编写 Parcelable 时出现 StackOverflowError

java - 具有基本身份验证和 OAuth 订单问题的 Spring Boot Security

java - 如何在Windows 10上扩展jMeter 5.1.1的HEAP SIZE

asp.net - 未指定 SMTP 主机

java - setCharacterEncoding 问题

java - Spring Security + Scratch Java 扩展

c# - 发送电子邮件 MVC 时出错

linux - 使用 Amavis 配置第二个内容过滤器

java - 从 PUT HttpServletRequest 获取参数?