Search code examples
javasmtpjakarta-mail

Sending mail using JavaMail - port 25, STARTTLS, authentication


I'm trying to send an email message to a SMTP server that listens on port 25, uses STARTTLS and requires authentication.

As far as I understand, the client should

  • greet the server with EHLO clientName
  • initiate TLS using STARTTLS
  • authenticate itself using AUTH LOGIN
  • go on with deliverying the email using RCPT TO, etc

My simplified code is

String protocol = "smtp";

Properties props = new Properties();
props.put("mail.debug", "true");
props.put("mail." + protocol + ".auth", true);
props.put("mail." + protocol + ".host", smtpHost);
props.put("mail." + protocol + ".starttls.required", true);

Session session = Session.getInstance(props);

InternetAddress[] recipients = InternetAddress.parse(username);

Message message = buildMessage(session, username, recipients);

Transport t = session.getTransport(protocol);
t.connect(username, password);

t.sendMessage(message, recipients);

As far as I understand this should work, but the debug output shows that it hangs at

STARTTLS
220 2.0.0 Ready to start TLS

Removing the starttls.required property leads to the server denying access, since the AUTH command is never present unless STARTTLS is issued

MAIL FROM:<[email protected]>
250 2.1.0 Ok
RCPT TO:<[email protected]>
554 5.7.1 Service unavailable; Client host [50.16.63.26] blocked using zen.spamhaus.org; http://www.spamhaus.org/query/bl?ip=50.16.63.26

What's the proper incantation to get Javamail to work with my setup?


Solution

  • Turns out that the original code was working. I was sent of by two mistakes:

    • I did not check the actual email account to see whether the email was delivered - and it was.
    • I was using a thread pool which was not shut down therefore the program appeared to be hanging

    OTOH, it would be nice for the Javamail debug mode to let me know when the message was actually sent.