Aug 12

Multipart emails can be used to send html content with JavaMail. If you want to use images in the html content you can either specify the url of the image on an external server, or you can embed the image in the email itself.

To embed an image in your mail you need to assign it a cid, which you can then reference in your html img tag. Here is an example that demonstrates embedding an image and use of cid.

Properties sessionProperties = System.getProperties();
sessionProperties.put("", smtpServer);
Session session = Session.getDefaultInstance(sessionProperties, null);

// Create message

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
		to, false));

// Add html content
// Specify the cid of the image to include in the email

String html = "<html><body><b>Test</b> email <img src='cid:my-image-id'></body></html>";
Multipart mp = new MimeMultipart();
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(html, "text/html");

// add image in another part

MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new FileDataSource(imagePath);
imagePart.setDataHandler(new DataHandler(fds));
// assign a cid to the image
imagePart.setHeader("Content-ID", "my-image-id");


// Send the message


written by objects \\ tags: , , ,

7 Responses to “How to embed images in HTML mail using JavaMail”

  1. Andres Says:

    thx for your i get it work with your message and
    thx again!!

  2. Tariq Says:

    Thanks , it is simple and straightforward 🙂

  3. objects Says:

    Thats how we like it. Thanks for taking the time to leave a comment.

  4. dinesh Says:

    what is the image path should I give when the image is present in the appserver which is deployed along with the ear. I am getting filenot found exception when i give the absolute path on the server

  5. objects Says:

    Sounds like your image is inside a war in which case you can’t use a FileDataSource. Instead try using a URLDataSource

  6. srav Says:

    excuse me what to give in “my-image-id” is that an image path ??

    and where should i give my image path

  7. objects Says:

    The image is added as part of the image (see line 25)

Leave a Reply

You must be logged in to post a comment.