In fact, there are two standardized types of secure mail sending:
- ESMTP protocol, working with or without encryption. Requires "pure" (non-SSL) sockets to be used. With "starttls" command, communication can be upgraded to full SSL. RFC-defined port is 587.
- SMTP protocol over the SSL transport. Requires SSL sockets to be used from the beginning. RFC-defined port is 465.
In order to configure JavaMail for ESMTP, following code is needed:
Properties properties = new Properties();
properties.put("mail.smtp.starttls.enable", "true")
final javax.mail.Session session = javax.mail.Session.getInstance(properties);
while for SMTP over SSL, use following:
Properties properties = new Properties();
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
final javax.mail.Session session = javax.mail.Session.getInstance(properties);
That's basically it. I tested following properties with GMail account, using both "SMTP over SSL" and "ESMTP with STARTTLS" options and it worked smoothly.
Following some most commonly experienced errors/exceptions with short descriptions:
- com.sun.mail.smtp.SMTPSendFailedException: 554 5.7.1 Sender address rejected.
In case of many providers (like "o2.pl") means that only account owner (like "user@o2.pl") is allowed as the message sender. - javax.mail.MessagingException: Could not connect to SMTP host: smtp.live.com, port: 465; nested exception is: java.net.ConnectException: Connection timed out
Basically thrown when requested port isn't open. In the mail world usually means that server doesn't offer configured secure protocol (for example Hotmail doesn't offer pure SSL connection) - com.sun.mail.smtp.SMTPSendFailedException: 553 From address not verified
Means that sender address needs to be verified (enabled) in account's configuration. Can be experienced with for example Yahoo! free accounts. - javax.mail.AuthenticationFailedException: 535-5.7.1 Username and Password not accepted.
Send by server if user or password used for authentication failed. Usually means that server requires full user name (user@server.com) to be used.
If above solution fails (or experienced exception is different than listed), you can always enable JavaMail debug with following property:
properties.put("mail.smtp.debug", "true");
There is also nice shell tool, very useful for checking secure SMTP account's features, called "smtp-cli". You can grab it here.