Goal
I want to implement a health check for an SMTP server. This healthcheck should include authentication so that I know not only know if the server is available but if I will be able to send emails using the given certificate.
I understand that this is possible using Telnet.
If possible I would like something a little more highlevel. At the moment I'm using javax.mail.Session
, javax.mail.Transport
, etc.
Questions
Is it possible to verify if an SMTP server will (likely) accept my request by authenticating using a certificate, without sending something like a testmail to the server using simple java API?
Also another question I have is if i should use a Session for a MimeMessage and then send these using the static Transport#send method. Or should can I use something where I get an instance. Main thing I would like to achieve is to retrieve the returncode from the server also in succesful cases.
I'm also okay with using a different library.
For reference some code of how I'm preparing the session and messages 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;
}
}
And how I then send the mails.
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);
}
}