Showing posts with label javamail. Show all posts
Showing posts with label javamail. Show all posts

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 = "";
      //String to = "";
      //String to = "";

      // Sender's email ID
      String from = "";

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

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

      // Setup mail server   ""
      properties.setProperty("", host);

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

         // 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.
                                  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");

//add image part
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(new FileDataSource("/home/gauravp/mail/NSAwarnsofpowergridshutdown.jpg")));

         // Send message

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