0
我编写了下面的servlet,它以.eml格式(使用JavaMail)生成的电子邮件作为响应。浏览器检测到MIME类型并在收到响应时打开一个电子邮件应用程序(Microsoft Live在我的案例中)。 “X-Unsent”被设置为“1”,所以当电子邮件被打开时,它可以被编辑和发送。JavaMail:内嵌图像生成不正确
电子邮件内容为带内联图像的HTML。当我打开生成的电子邮件时,我可以看到没有问题的内容。但是,当我输入地址并尝试发送电子邮件时,我收到消息“找不到一个或多个图像,是否要继续?”。无论如何我都会发送它,当我检查电子邮件收件人的帐户时,收到的是电子邮件,而不是将图像内联,而是附上。内嵌图像生成的方式似乎有些不妥。有任何想法吗?
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("message/rfc822");
response.setHeader("Content-Disposition", "attachment; filename=\"email.eml\"");
PrintWriter out = response.getWriter();
String eml = null;
try {
Message message = new MimeMessage(Session.getInstance(System.getProperties()));
message.addHeader("X-Unsent", "1");
message.setSubject("email with inline image");
// This mail has 2 parts, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");
// first part (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H1>This is the image: </H1><img src=\"cid:image\">";
messageBodyPart.setContent(htmlText, "text/html");
multipart.addBodyPart(messageBodyPart);
// second part (the image)
messageBodyPart = new MimeBodyPart();
String filePath = "C:/image.png";
DataSource fds = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-Type", "image/png");
messageBodyPart.setHeader("Content-ID", "image");
messageBodyPart.setDisposition(MimeBodyPart.INLINE);
// add image to the multipart
multipart.addBodyPart(messageBodyPart);
// put everything together
message.setContent(multipart);
ByteArrayOutputStream os = new ByteArrayOutputStream();
message.writeTo(os);
eml = new String(os.toByteArray(),"UTF-8");
}
catch (MessagingException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
out.print(eml);
out.flush();
out.close();
}
谢谢,这个工作,但是我不得不使用'messageBodyPart.attachFile(文件路径)',预计一个参数。 – ps0604 2014-10-10 13:10:56
您仍然必须使用JavaMail 1.4.x,新方法已添加到JavaMail 1.5中。获取最新版本[这里](https://java.net/projects/javamail/pages/Home)。 – 2014-10-11 07:01:36