Monday, January 13, 2014

Send HTML mail with embedded Image using Javamail API

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class Testmail
{
   public static void main(String [] args)
   {
   
      // Recipient's email ID needs to be mentioned.
      String to = "golupant@gmail.com";
      //String to = "hemantvsn@gmail.com";
      //String to = "dileep.multimedia@gmail.com";

      // Sender's email ID
      String from = "test@gmail.com";

      // sending email from localhost
      String host = "localhost";

      // Get system properties
      Properties properties = System.getProperties();

      // Setup mail server   "smtp.gmail.com"
      properties.setProperty("server1.vo.com", host);

      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);


//Create multipart message
MimeMultipart multipart = new MimeMultipart("related");


         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO,
                                  new InternetAddress(to));

         // Set Subject: header field
         message.setSubject("This is my Subject");


         //add text part
BodyPart bodyPart = new MimeBodyPart();
         String htmlText = "<html><body><img src='cid:myimageid' /><p>this is my html body</p></body></html>";
bodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(bodyPart);

//add image part
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(new FileDataSource("/home/gauravp/mail/NSAwarnsofpowergridshutdown.jpg")));
imagePart.addHeader("Content-ID","<myimageid>");
multipart.addBodyPart(imagePart);

message.setContent(multipart);
       
         // Send message
         Transport.send(message);

         System.out.println("Sent message successfully....");
      }catch (Exception e) {
         e.printStackTrace();
      }
   }
}