Java mail and SMTP: “501 HELO requires valid address”

I was trying to send a mail through Java the other day and kept stumbling upon the following exception:

javax.mail.MessagingException: 501 HELO requires valid address

I thought it was caused by an authentication problem or my provider preventing me from sending from a random address.
The former I tried to address by making sure I was fully authenticated as to prove I was not trying to send spam. In java mail the following properties are relevant for sending authenticated mail using TLS:

-Dmail.smtp.host=<your smtp server>
-Dmail.smtp.port=587
-Dmail.smtp.username=<your username>
-Dmail.smtp.password=<your password>
-Dmail.smtp.auth=true
-Dmail.smtp.starttls.enable=true

and setting an authenticator on the mail session object:

Session session = Session.getDefaultInstance(System.getProperties(), new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MAIL_USER, MAIL_PWD);
}
});

The latter I tried to address by sending from an alias that was associated with the original mailbox (user/pwd combo). Yet I kept getting the same exception.

Looking up the SMTP protocol and testing with telnet, I found out that normally you are supposed to provide a domain name when issueing the EHLO or HELO command. Since the api does not provide any methods for that, I looked for some more properties and indeed, it turns out you need to set

-Dmail.smtp.localhost

to make it provide the hostname for the EHLO command. According to the docs:
Should not normally need to be set if your JDK and your name service are configured properly.” but apparently my case was not normal 🙂

Also worth noting is that you can turn on debug output with:

session.setDebug(true);

Leave a Reply

Your email address will not be published. Required fields are marked *