Using JavaMail with TLS Using JavaMail with TLS java java

Using JavaMail with TLS


We actually have some notification code in our product that uses TLS to send mail if it is available.

You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.

Properties props = new Properties();props.put("mail.smtp.starttls.enable","true");props.put("mail.smtp.auth", "true");  // If you need to authenticate// Use the following if you need SSLprops.put("mail.smtp.socketFactory.port", d_port);props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");props.put("mail.smtp.socketFactory.fallback", "false");

You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).


Good post, the line

props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

is mandatory if the SMTP server uses SSL Authentication, like the GMail SMTP server does. However if the server uses Plaintext Authentication over TLS, it should not be present, because Java Mail will complain about the initial connection being plaintext.

Also make sure you are using the latest version of Java Mail. Recently I used some old Java Mail jars from a previous project and could not make the code work, because the login process was failing. After I have upgraded to the latest version of Java Mail, the reason of the error became clear: it was a javax.net.ssl.SSLHandshakeException, which was not thrown up in the old version of the lib.


The settings from the example above didn't work for the server I was using (authsmtp.com). I kept on getting this error:

javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?

I removed the mail.smtp.socketFactory settings and everything worked. The final settings were this (SMTP auth was not used and I set the port elsewhere):

java.util.Properties props = new java.util.Properties();props.put("mail.smtp.starttls.enable", "true");