Sending mail with java mail javax Mailer encrypted SSL or TLS
This is about sending mail, so we are talking about a SMTP server
The code
Properties props = new Properties();
if (Integer.parseInt(port) == 465) // SSL
{
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "true");
}
else
{
props.put("mail.smtp.starttls.enable", "true");
}
Session mailSession = Session.getInstance(props);
mailSession.setDebug(false);
MimeMessage message = new MimeMessage(mailSession);
message.setSubject(subject);
message.setContent(messageString, "text/plain");
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
message.setFrom(new InternetAddress(recipients));
Transport transport = mailSession.getTransport("smtp");
transport.connect(host, Integer.parseInt(port), username, password);
transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
transport.close();
Setting the right parameters
For example with gmail, the settings are :
- Gmail SMTP server address: smtp.gmail.com
- Gmail SMTP user name: Your full Gmail address (e.g. example@gmail.com)
- Gmail SMTP password: Your Gmail password
- Gmail SMTP port (TLS): 587
- Gmail SMTP port (SSL): 465
More reading
The official FAQ is actually great
www.oracle.com/technetwork/java/javamail/faq/index.html
Recent Comments