Embedding a Logo Inside an Email Body

Here’s the Java code and steps to be followed for adding an in-line image to an email body, which allows an email message to be received without the image being attached to the message with a paperclip icon.

NOTE: Please note that in this Java code, message is of type javax.mail.Message.

 

  1. Create a UID in your code. For our example, we have hardcoded a UID for cid value which is "image12345". The UID will be used in the following places:

    <img src=\"cid: image12345\">

    messageBodyPart.setHeader("Content-ID", "< image12345>");

     

  2. Change the content type from image/png to the related type, in case the extension is something other than png (e.g. jpg).

  3.  

  4. Create a MimeMultipart with multipart “related”. Multipart “related” indicates that the parts of the email are related.

    MimeMultipart multipart = new MimeMultipart();

    multipart.setSubType("related");

  5.  

  6. Attach the email and set the Content_type for the image.

    messageBodyPart.attachFile("C:\\temp\\CMiC_Email_Tmplt_logo.png");

    messageBodyPart.setHeader("Content-Type", "image/png");

  7.  

  8. Make sure the Content-Type is set after attaching the image, using the same sequence shown in Step 4, otherwise, the paperclip icon will not be hidden in the Outlook email preview.

    Here is an example of the Java code using the UID "image12345".

     

    // This mail has 2 part, the BODY and the embedded image

    MimeMultipart multipart = new MimeMultipart();

    multipart.setSubType("related");

     

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    String htmlText = "<H1>Hello</H1><img src=\"cid: image12345\">";

    messageBodyPart.setText(htmlText, "utf-8", "html");

    multipart.addBodyPart(messageBodyPart);

     

    // second part (the image)

    messageBodyPart = new MimeBodyPart();

    messageBodyPart.setHeader("Content-ID", "< image12345>");

    messageBodyPart.attachFile("C:\\temp\\CMiC_Email_Tmplt_logo.png");

    messageBodyPart.setHeader("Content-Type", "image/png");

    messageBodyPart.setDisposition(MimeBodyPart.INLINE);

     

    // add image to the multipart

    multipart.addBodyPart(messageBodyPart);

    // put everything together

    message.setContent(multipart);