I coded the servlet below that generates as a response an email in .eml format (using JavaMail). The browser detects the mime type and opens an email app (Microsoft Live in my case) when the response is received. "X-Unsent" is set to "1" so when the email is opened it can be edited and sent.
The email content is HTML with an image inline. When I open the generated email I can see the content with no issues. But when I enter an address and try to send the email I get the message "one or more images could not be found, do you want to continue?". I send it anyways and when I check the account of the email recipient the email is received however instead of having the image inline, it is attached. It seems that something is wrong with the way inline images are generated. Any ideas?
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();
}
Try this simpler version that might also fix the problem:
// 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);