JavaMail:生成的内联图像不正确

时间:2014-10-08 23:56:29

标签: servlets javamail

我编写了下面的servlet,它以.eml格式生成一个电子邮件作为响应(使用JavaMail)。浏览器检测到mime类型并在收到响应时打开电子邮件应用程序(在我的情况下为Microsoft Live)。 " X-未发送"设置为" 1"因此,当电子邮件打开时,它可以被编辑和发送。

电子邮件内容为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();

}

1 个答案:

答案 0 :(得分:0)

尝试这个更简单的版本,也可能解决问题:

 // first part (the html)
 MimeBodyPart messageBodyPart = new MimeBodyPart();
 String htmlText = "<H1>This is the image: </H1><img src=\"cid:image\">";
 messageBodyPart.setText(htmlText, null, "html");
 multipart.addBodyPart(messageBodyPart);

 // second part (the image)
 messageBodyPart = new MimeBodyPart();
 String filePath = "C:/image.png";
 messageBodyPart.attachFile(filePath, "image/png", "base64");
 messageBodyPart.setContentID("<image>");

 // add image to the multipart
 multipart.addBodyPart(messageBodyPart);