我想将一个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)
有人可以帮我解决这个问题吗? :(
答案 0 :(得分:1)
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);