GAE将PNG图像附加到电子邮件中

时间:2014-03-18 09:55:26

标签: google-app-engine java-ee javamail

我想将一个png图像文件附加到GAE上的电子邮件中。一开始我从以下开始:

MimeMessage msg = new MimeMessage(session);
... 
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile("/templates/header_nr1.png");
...
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(textPart);
multipart.addBodyPart(htmlPart);
multipart.addBodyPart(imagePart); 

但是这导致了

pl.insert.services.ExceptionHandler handleUnknownException:java.security.AccessControlException:access denied ("java.io.FilePermission" "/templates/header_nr1.png" "read")

以及使用任何可用解决方案无法解决的许多其他变体。

根据https://developers.google.com/appengine/docs/java/mail/usingjavamail#Multi_Part_Messages 我已将检索文件的方式更改为:

InputStream fileIs = MailServiceImpl.class.getResourceAsStream("/templates/header_nr1.png");
byte[] headerImage = IOUtils.toByteArray(fileIs);

String cid = "header_nr1";
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setFileName("header_nr1.png");
DataSource src = new ByteArrayDataSource(headerImage, "image/png");
imagePart.setDataHandler(new DataHandler(src));
imagePart.setContent(headerImage, "image/png");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);

现在我有了

javax.mail.SendFailedException: Send failure (javax.mail.MessagingException: Converting attachment data failed)
at javax.mail.Transport.send(Transport.java:163)
at javax.mail.Transport.send(Transport.java:48)

有人可以帮我解决这个问题吗? :(

1 个答案:

答案 0 :(得分:1)

Oki,最后我已经解决了这个问题。这是GAE上附加内联PNG图像的MultiPart电子邮件的处方:

String headerImageCid = "header";
InputStream pngInputStream = MailServiceImpl.class.getResourceAsStream("/images/" +     headerImageCid + ".png");
DataSource ds = new ByteArrayDataSource(pngInputStream, "image/png");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setFileName(headerImageCid + ".png");
imagePart.setHeader("Content-Type", "image/png");
imagePart.addHeader("Content-ID", "<" + headerImageCid + ">");

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

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

Transport.send(msg);