B.Z.B
B.Z.B

Reputation: 471

Insert Image Directly into an HTML Template Using Javamail

Hey all, I've seen a lot of topics on this, but not quite what I am looking for.

Essentially when I get to sending my Javamail message I'll have my image as a byte[] object and I'll have a string that contains the html template. What I am looking to do is not store it on the server (didn't want to try to deal with the upkeep on keeping the image stored on the server, and we'll have limited space to work with). I'd like to take the byte[] object that I already have and directly store it within the html template, making sure it's in the correct image tag. Is there a way I could do this? Basically I want to stick a message.setContent("blah","image/jpg"); directly into the html template at a specific spot.

Hopefully I'm making sense here...

Another Idea I was thinking was add the image as an attachment and just reference the attachment when displaying the html template....if that is possible.

Upvotes: 2

Views: 11481

Answers (2)

RealHowTo
RealHowTo

Reputation: 35372

You add the image as an attachment and then you make a reference to it with a "cid" prefix.

//
// This HTML mail have to 2 part, the BODY and the embedded image
//
MimeMultipart multipart = new MimeMultipart("related");

// first part  (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>Hello</H1><img src=\"cid:[email protected]\">";
messageBodyPart.setContent(htmlText, "text/html");

// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
  ("C:\\images\\foo.gif");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID","<[email protected]>");

// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);

Upvotes: 7

objects
objects

Reputation: 8677

Try the following which uses a ByteArrayDataSource to include your image bytes in the mail

// 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");
mp.addBodyPart(htmlPart);

// add image in another part

MimeBodyPart imagePart = new MimeBodyPart();
DataSource fds = new ByteArrayDataSource(imageBytes, imageType);
imagePart.setDataHandler(new DataHandler(fds));

// assign a cid to the image

imagePart.setHeader("Content-ID", "<my-image-id>"); // Make sure you use brackets < >
mp.addBodyPart(imagePart);

message.setContent(mp);

Adapted from example @ http://helpdesk.objects.com.au/java/how-to-embed-images-in-html-mail-using-javamail

Upvotes: 1

Related Questions