0

I am trying to embed an image on a Freemarker ftl template to send as an email, I've based on this question Feemarker writing images to html, I did the exact same thing as this question said, but the email is being generated like this

What may be causing this error, and how to fix it?

My template looks like this

<img alt="My image" src="${imgAsBase64}" />

The image is a Chart, and I get the Base64 String, which I called imageBase64Str, via a Primefaces JavaScript function that generates the Base64 of the chart image, I pass it to the the bean and pass the parameter to the template like this

String encoded = imageBase64Str.split(",")[1];
byte[] decoded = Base64.decodeBase64(encoded);
String imgDataAsBase64 = new String(decoded);
String imgAsBase64 = "data:image/png;base64," + imgDataAsBase64;
emailParams.put("imgAsBase64", imgAsBase64);

1 Answers1

1

String encoded = imageBase64Str.split(",")[1]; is suspicious. Looks like you are changing the base 64 string generated in some different way. Is the image actually a png or it's in another format? I think that if you remove that split and just do emailParams.put("imgAsBase64", imageBase64Str); it may work.

However you need to consider that this solution won't work for many email clients. According to this link https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/ Base64 embedded images are not supported on a few major email clients, web and standalone, including Gmail and Outlook. Given that they are the most common email clients you don't want to deliver a solution that doesn't work on them or most of your users are gonna be unhappy.

IMO your best bet is to host the images in a server and use fully qualified URLs in your freemarker template.

An alternative is using the attachment and reference them in the html source as explained here: https://stackoverflow.com/a/36870709/2546299 but it require changes on the way the emails are sent (need to add the attachments) so it may not be suitable for your case.

Totò
  • 1,824
  • 15
  • 20
  • Hi @Joao Victor Oliveira Santos, was my answer of any help? – Totò Jul 27 '17 at 02:54
  • 1
    Sorry for the delay, the code was correct, the problem was, as you pointed, the fact that most of the big email providers doesn't support Base64 images. The solution was host the images in the server and use html as you sugested – Joao Victor Oliveira Santos Jul 29 '17 at 07:12