Search code examples
javagoogle-app-enginejakarta-mail

Sending an email with inline picture on App Engine since 1.9.0


I am currently trying to send an email with a picture inside the mail using the Google App Engine 1.9.5. This features is availible only from the version 1.9.0 of the SDK :

Users now have the ability to embed images in emails via the Content-Id attachment header.
https://code.google.com/p/googleappengine/issues/detail?id=965
https://code.google.com/p/googleappengine/issues/detail?id=10503

Source : https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes

This is my code :

Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("[email protected]", "xxx.com newsletter"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("[email protected]", "Leo Mieulet"));
msg.setSubject("Inline image test : "+new Date().getTime());

String imageCid = "graph";
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setFileName(imageCid + ".png");
imagePart.setHeader("Content-Type", "image/png");
imagePart.addHeader("Content-ID", "<" + imageCid + ">");

String htmlBody = "My html text... <img src=\"cid:"+imageCid+"\"> ... ends here.";
// Create alternate message body.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>"+htmlBody+"</body></html>", "text/html");

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

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

Transport.send(msg);

I receive an email which looks like : enter image description here Could anyone help me with the problem ?


Solution

  • Based on the imageBase64 variable name, you seems to give to the ByteArrayDataSource the image already encoded in Base64. You should directly use the image byte array without Base64.encode() it.