【问题标题】:Verify SMTP server authentication via java api (Healthcheck including AUTH)通过 java api 验证 SMTP 服务器身份验证(包括 AUTH 的健康检查)
【发布时间】:2020-06-24 14:54:01
【问题描述】:

目标

我想为 SMTP 服务器实施健康检查。此运行状况检查应包括身份验证,以便我不仅知道服务器是否可用,而且知道我是否能够使用给定的证书发送电子邮件。

我知道这个is possible using Telnet。

如果可能的话,我想要一些更高级的东西。目前我正在使用javax.mail.Session、javax.mail.Transport等。

问题

是否可以通过使用证书进行身份验证来验证 SMTP 服务器是否(可能)接受我的请求,而不使用简单的 java API 向服务器发送测试邮件之类的东西?

我还有一个问题是我是否应该为 MimeMessage 使用 Session,然后使用静态 Transport#send 方法发送它们。或者我应该在我得到一个实例的地方使用一些东西。我想要实现的主要目标是在成功的情况下也从服务器检索返回码。

我也可以使用不同的库。

供参考我如何准备会话和消息 atm 的一些代码。

public class SmtpMailService {

    public Session prepareSession() {
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        return Session.getInstance(properties, null);
    }

    public List<MimeMessage> sendMessages(List<MimeMessage> messages) {
        Iterator<MimeMessage> m = messages.iterator();

        while (m.hasNext()) {
            MimeMessage currentMessage = m.next();
            try {
                Transport.send(currentMessage);
                m.remove();
            } catch (MessagingException e) {
                break;
            }
        }

        List<MimeMessage> mailsWithError = StreamUtils.asList(m);
        return mailsWithError;
    }
}

然后我如何发送邮件。

public class SmtpMailSenderService {
    private SmtpMailService mailerService;

    public List<SmtpEmailNotificationRecipient> sendNotificationMails(final List<SmtpEmailNotificationRecipient> recipients,
            final SmtpMailTemplate templateId, final Map<String, String> templateValues) {

        // templating stuff

        final Session smtpSession = mailerService.prepareSession();
        final List<MimeMessage> messages = mailerService.prepareMessages(smtpSession, recipients, email);

        final List<MimeMessage> unsentMessages = mailerService.sendMessages(messages);

        return collectRemainingRecipients(unsentMessages);
    }
}

【问题讨论】:

    标签: java email smtp jakarta-mail


    【解决方案1】:

    您无法判断服务器是否允许您在不实际发送邮件的情况下发送邮件。然后收件人也很重要。

    您可以让 JavaMail 在成功时抛出异常,该异常将包含返回码。将mail.smtp.reportsuccess Session 属性设置为true。请参阅smtpsend.java 示例程序。

    如果您已经有一个 Transport 对象,您最好使用它来代替静态发送方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 2011-03-05
      • 2021-06-16
      • 1970-01-01
      相关资源
      最近更新 更多