自1.9.0以来在App Engine上发送带有内联图片的电子邮件

时间:2014-05-21 12:03:04

标签: java google-app-engine javamail

我目前正在尝试使用Google App Engine 1.9.5在邮件中发送带有图片的电子邮件。此功能仅适用于SDK的1.9.0版本:

Users now have the ability to embed images in emails via the Content-Id attachment header.
https://code.google.com/p/googleappengine/issues/detail?id=965
https://code.google.com/p/googleappengine/issues/detail?id=10503

来源:https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes

这是我的代码:

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("leo.mieulet@xxx.com", "xxx.com newsletter"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("leo.mieulet@xx.com", "Leo Mieulet"));
msg.setSubject("Inline image test : "+new Date().getTime());

String imageCid = "graph";
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setFileName(imageCid + ".png");
imagePart.setHeader("Content-Type", "image/png");
imagePart.addHeader("Content-ID", "<" + imageCid + ">");

String htmlBody = "My html text... <img src=\"cid:"+imageCid+"\"> ... ends here.";
// Create alternate message body.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>"+htmlBody+"</body></html>", "text/html");

final Multipart multipart = new MimeMultipart();
multipart.addBodyPart(htmlPart);
multipart.addBodyPart(imagePart);

msg.setContent(multipart);
msg.saveChanges();

Transport.send(msg);

我收到的电子邮件如下: enter image description here 任何人都可以帮我解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

基于imageBase64变量名,您似乎向ByteArrayDataSource提供已在Base64中编码的图像。你应该直接使用没有Base64.encode()的图像字节数组。

答案 1 :(得分:1)

太棒了! ;)

如果要以纯HTML显示图像(在app-engine doGet()上下文中):

//byte[] imgContent =  the content of your image
Base64 base64 = new Base64(); 
imgContent = base64.encode(imgContent);
resp.getWriter().write("<html><img src='data:image/png;base64,"+new String(imgContent)+"'></html>");

正如@ benoit-s所说,你不需要在base64中对图像内容进行编码。 我刚刚编辑了这一行:

DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");

//byte[] imageAsByteArray =  the content of your image
DataSource ds = new ByteArrayDataSource(imageAsByteArray, "image/png");