I have an HTML template with <img>
tag to display a QR code representation of a user ID, for that I simply used DATA URL technique src="data:image/png;base64, base64String
as suggested by https://sendgrid.com/blog/embedding-images-emails-facts/ under the section Inline Embedding (Base64 Encoding).
This is working in outlook, but there seems to be a problem for Gmail. What is the best way to display this QR code in email clients, especially in Gmail. Note that, I do not have an actual image file as the QR is generated from the user ID, at most I just have the byte array representing the QR image.
I am using sendgrid to send the emails.
As suggested by this answer https://stackoverflow.com/a/29205203/2017536 Here is how this problem can be solved using javax.mail package
@Autowired
private JavaMailSender mailSender;
private void sendMail(String to, String subject, String bodyPlainText, String bodyHtml, String contentId, String base64Image) {
try {
MimeMessage message = mailSender.createMimeMessage();
message.setSubject(subject);
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(bodyPlainText, "text/plain; charset=UTF-8");
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(bodyHtml, "text/html; charset=UTF-8");
Multipart multiPart = new MimeMultipart("alternative");
// create a new imagePart and add it to multipart so that the image is inline attached in the email
byte[] rawImage = Base64.getDecoder().decode(base64Image);
BodyPart imagePart = new MimeBodyPart();
ByteArrayDataSource imageDataSource = new ByteArrayDataSource(rawImage,"image/png");
imagePart.setDataHandler(new DataHandler(imageDataSource));
imagePart.setHeader("Content-ID", "<qrImage>");
imagePart.setFileName("someFileName.png");
multiPart.addBodyPart(imagePart);
multiPart.addBodyPart(textPart);
multiPart.addBodyPart(htmlPart);
message.setContent(multiPart);
mailSender.send(message);
} catch (MessagingException exception) {
//log error
}
}
And in your html template you should have <img src="cid:qrImage" alt="qr code">