Howto: Send Mail Over SMTPS In Java
Introduction
This tutorial will show you, with an example, how to send mail in Java over SMTPS. Nowadays, providers try to use the extended version of smtp: smtps, where the s stands for the SSL protocol. SMTP, or Simple Mail Transfer Protocol, is the de facto standard for email transmissions across the internet where the SSL protocol, or Secure Socket Layer, provides an encrypted, secure connection.
Example code
In the example given, we will use the smtps server of Google. To use this server, you will need a Gmail account. We will assume the fictive email ‘mail@gmail.com’ as mail account with ‘password’ as password. We will also use the JavaMail library.
import java.util.Properties; import javax.mail.Message; import javax.mail.Multipart; import javax.mail.Session; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import com.sun.mail.smtp.SMTPSSLTransport; public static void sendMail(String to, String from, String subject, Multipart content) { try { // create properties Properties props = System.getProperties(); // < -- authorization, i.e. account & password is required --> props.put("mail.smtps.auth", "true"); // < -- it is important you use the correct port. smtp uses 25, smtps 465 --> props.put("mail.smtps.port", "465">); // < -- put the smtps server host address here --> props.put("mail.smtps.host", "smtp.gmail.com"); // create session Session session = Session.getDefaultInstance(props); session.setDebug(true); // create content MimeMultipart msgContent = new MimeMultipart("alternative"); // Text Mail MimeBodyPart html = new MimeBodyPart(); // < -- we will send plain text, "text/html" is possible as well --> html.setContent(content, "text/plain"); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", "text/plain; charset=iso-8859-1"); msgContent.addBodyPart(html); MimeMessage msg = new MimeMessage(session); msg.setContent(content); // set sender and recipient msg.setFrom(new InternetAddress(from)); msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); msg.setSubject(subject); // transport the message // < -- we will send the message over smtps --> SMTPSSLTransport transport = (SMTPSSLTransport)session.getTransport("smtps"); // connect to server // < -- fill in gmail email address and password --> transport.connect("smtp.gmail.com", "mail@gmail.com", "password"); // send the message transport.sendMessage(msg, msg.getAllRecipients()); // close the connection transport.close(); } catch> (Exception e) { e.getStackTrace(); return; } }
Thanks a lot for this tutorial, I will be using it a lot!