使用Javamail将图像直接插入HTML模板

时间:2011-03-15 17:49:10

标签: java html css image javamail

嘿所有,我已经看到了很多这方面的话题,但不是我想要的。

基本上当我发送我的Javamail消息时,我将把我的图像作为byte []对象,并且我将有一个包含html模板的字符串。我想要做的是不将它存储在服务器上(不想在保持图像存储在服务器上时试图处理维护,我们将有有限的空间来处理)。我想把我已经拥有的byte []对象直接存储在html模板中,确保它在正确的图像标签中。有没有办法可以做到这一点?基本上我想坚持一个message.setContent(“blah”,“image / jpg”);直接进入特定地点的html模板。

希望我在这里有意义......

我想到的另一个想法是将图像添加为附件,并在显示html模板时引用附件....如果可行的话。

2 个答案:

答案 0 :(得分:7)

您将图像添加为附件,然后使用“cid”前缀对其进行引用。

//
// 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);

完整示例here

答案 1 :(得分:1)

尝试使用ByteArrayDataSource在邮件中包含图像字节的以下内容

// 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);

改编自示例@ http://helpdesk.objects.com.au/java/how-to-embed-images-in-html-mail-using-javamail