通过 java api 验证 SMTP 服务器身份验证(健康检查包括 AUTH)

Verify SMTP server authentication via java api (Healthcheck including AUTH)

目标

我想对 SMTP 服务器进行健康检查。此健康检查应包括身份验证,这样我不仅可以知道服务器是否可用,还可以知道我是否能够使用给定的证书发送电子邮件。

我明白这个is possible using Telnet

如果可能的话,我想要更高层次的东西。目前我正在使用 javax.mail.Sessionjavax.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);
    }
}

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

您可以让 JavaMail 在成功时抛出异常,异常将包含 return 代码。设置mail.smtp.reportsuccess Session property to true. See the smtpsend.java示例程序。

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