Hilde
Hilde

Reputation: 363

html email with reference to an image as base64 String

I would like to send an email with the Java Mail API (javax.mail). The message must contain html and inside there is a reference to an image. There is a challenge, because no reference to a physical file on disk is allowed but instead I have created a base64 string (http://www.base64-image.de/step-1.php) for that image and copied that data to a static String variable. With javax.mail I build a message of type MulitPart with two parts. The first part is the html itself and the second part is the image. The html part reference to the image via <img src="cid:image-id"/>.

Message msg = new MimeMessage(session);
Multipart multipart = new MimeMultipart("related");
BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
                "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
multipart.addBodyPart(htmlPart);

public static final String base64logo = "/9j/4AAQSkZJRgABAQEASABIAAD/4QBe…"; // ein ganz langer String erzeugt über http://www.base64-image.de/step-1.php

sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] imageByte = decoder.decodeBuffer(base64logo);
InternetHeaders header = new InternetHeaders();
BodyPart imgPart=new MimeBodyPart(header, imageByte);
imgPart.setHeader("Content-ID","the-img-1");
imgPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imgPart);
msg.setContent(multipart);

Unfortunately the image is missing in the incoming email.

When I point to the file on my disk it is working:

DataSource ds=new FileDataSource("c:/temp/image001.jpg");
imgPart.setDataHandler(new DataHandler(ds));

We are developing with Talend and we cannot reference to external files because that would make the deployment process more complicate.

Can you find some wrong doings in my approach?

Kind regards Hilderich

Upvotes: 2

Views: 3128

Answers (2)

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

This has been asked before a long time ago. But I will answer this as I have faced the same issue, from my own answer here.

byte[] tile = DatatypeConverter.parseBase64Binary(base64logo);
BodyPart messageBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(tile, "image/jpeg"));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<the-img-1>");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);

Hope it will help someone.

Upvotes: 2

Karluqs
Karluqs

Reputation: 11

Try putting angle braces here

imgPart.setHeader("Content-ID","<the-img-1>");

I found this answer on the comments of an old post from this blog

http://www.jroller.com/eyallupu/entry/javamail_sending_embedded_image_in

In the comment of Aravind Velayudhan Nair

It worked for me!

Upvotes: 1

Related Questions