Aug 19, 2012

JavaMail API Part 4 - Using secured protocol

There are many security measures we can implement into the system. We will take a special case of gmail which uses STARTTLS. STARTTLS is an extension to plain text communication protocols, which offers a way to upgrade a plain text connection to an encrypted (TLS or SSL) connection instead of using a separate port for encrypted communication.

Here is the code for sending email using host which implements STARTTLS.

package com.test;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class SendMail {

   public static void main(String[] args) {

      String host = "";

      String from = "";

      String pass = "sender's password";

      Properties props = System.getProperties();

      props.put("mail.smtp.starttls.enable", "true"); // added this line

      props.put("", host);

      props.put("mail.smtp.user", from);

      props.put("mail.smtp.password", pass);

      props.put("mail.smtp.port", "587");

      props.put("mail.smtp.auth", "true");

      String[] to = {","};

      String fileAttachment = "F:\\emoticons\\yawn.gif";

      Session session = Session.getDefaultInstance(props, null);

      MimeMessage message = new MimeMessage(session);

      try {

         message.setFrom(new InternetAddress(from));

         InternetAddress[] toAddress = new InternetAddress[to.length];

         // To get the array of addresses

         for( int i=0; i < to.length; i++ ) { // changed from a while loop

            toAddress[i] = new InternetAddress(to[i]);


         for( int i=0; i < toAddress.length; i++) { // changed from a while loop

            message.addRecipient(Message.RecipientType.TO, toAddress[i]);


         message.setSubject("sending in a group");

         // create the message part 

         MimeBodyPart messageBodyPart = new MimeBodyPart();

         //fill message


         Multipart multipart = new MimeMultipart();


         // Part two is attachment

         messageBodyPart = new MimeBodyPart();

         DataSource source = new FileDataSource(fileAttachment);

         messageBodyPart.setDataHandler(new DataHandler(source));



         // Put parts in message


         Transport transport = session.getTransport("smtp");

         transport.connect(host, from, pass);

         transport.sendMessage(message, message.getAllRecipients());


      } catch (AddressException e) {


      } catch (MessagingException e) {



No comments: