I need to send an email using Javamail and TLS (not STARTTLS, but a dedicated smtp port just for SSL/TLS!). I only managed to find examples for gmail, that however use STARTTLS. Can somebody please post an example for normal SSL/TLS? Thank you very much!
2 Answers
The official examples for JavaMail with Gmail use SMTPS (i.e. SMTP over SSL/TLS on a dedicated port) and not STARTTLS. Essentially, the properties using JavaMail should be mail.smtps.*
instead of mail.smtp.*
.
If you want to force a specific version of SSL/TLS, for example TLSv1.0, you'll need to create your own SSLSocketFactory
, possibly wrapping the default SSLSocketFactory
(or anything else you would have customised), but you need to call sslSocket.setEnabledProtocols(new String[] { "TLSv1" })
before returning the socket.
You'll need to pass that SSLSocketFactory
either as an instance via the mail.smtps.ssl.socketFactory
configuration property, or as a fully qualified class name via mail.smtps.ssl.socketFactory.class
(in this case, you class must implement a static method called getDefault
).
To prevent MITM attacks, you also need to make the client verify the server host name: you need to set mail.smtps.ssl.checkserveridentity
to true
, since it seems to be false
by default.
For the records, based on Brunos answer:
private static void sendMailSSL(String host, int port, String user, String pass, String to, String from, String subj, String message) throws UnsupportedEncodingException, MessagingException
{
Properties props = System.getProperties();
props.put("mail.smtps.ssl.checkserveridentity", true);
Session session = Session.getDefaultInstance(props, null);
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from, from));
msg.addRecipients(RecipientType.TO, to);
msg.setSubject(subj);
msg.setText(message);
Transport t = session.getTransport("smtps");
try {
t.connect(host, port, user, pass);
t.sendMessage(msg, msg.getAllRecipients());
} finally {
t.close();
}
}
Please note that I didn't test if checkserveridentity is actually really considered. At least it really uses SSL :-)