简体   繁体   中英

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.

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:image@foo.com\">";
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","<image@foo.com>");

// add it
multipart.addBodyPart(messageBodyPart);

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

Complete example here

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM