Thursday, August 12, 2010

Embedding images in E-Mail





We have been using XML XSL transformation for generating the emails and it was working well . XML Provides the data and Styling is provided in XSL . It becomes tricky when including images . One easy way to do is to include images as URL . This may not be the right approach as the user may not be online when looking a the email and can be lost during forwarding .

Best way is to use javax.mail.internet.MimeMultipart and set the images as header .
Here is the example
XSL to include images will look like this

<img>
<xsl:attribute name="src">cid:image1</xsl:attribute>
<xsl:attribute name="border">0</xsl:attribute>
</img>


Include the images in the email service after the transformation


MimeMultipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();

messageBodyPart.setContent("All Email contents from Transformation", "text/html");
multipart.addBodyPart(messageBodyPart);

// add first image
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
("C:\\image_path");
messageBodyPart.setHeader("Content-ID","<image1>");
messageBodyPart.setDataHandler(new DataHandler(fds));
multipart.addBodyPart(messageBodyPart);

//add another image
messageBodyPart = new MimeBodyPart();
DataSource fds1 = new FileDataSource
("C:\\image-path");
messageBodyPart.setHeader("Content-ID","<image2>");
messageBodyPart.setDataHandler(new DataHandler(fds1));
multipart.addBodyPart(messageBodyPart);

message.setContent(multipart);


You will see the image replaced .Images are downloaded with the message and is replaced where the tag is used . It's solves all the issues related to using them as URL.