Freemarker 在 ftl 上嵌入图像

Freemarker embed image on ftl

我正在尝试在 Freemarker ftl 模板上嵌入图像以作为电子邮件发送,我基于这个问题 Feemarker writing images to html, I did the exact same thing as this question said, but the email is being generated like this

可能导致此错误的原因是什么,如何解决?

我的模板是这样的

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

图像是一个图表,我通过生成图表图像的 Base64 的 Primefaces JavaScript 函数获得了我称为 imageBase64Str 的 Base64 字符串,我将它传递给 bean 并传递像这样的模板参数

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);

String encoded = imageBase64Str.split(",")[1]; 可疑。看起来您正在更改以某种不同方式生成的 base 64 字符串。图像实际上是 png 还是其他格式?我认为如果您删除该拆分并只执行 emailParams.put("imgAsBase64", imageBase64Str); 它可能会起作用。

但是您需要考虑到此解决方案不适用于许多电子邮件客户端。根据此 link https://www.campaignmonitor.com/blog/email-marketing/2013/02/embedded-images-in-html-email/ Base64 嵌入式图像在一些主要的电子邮件客户端、Web 和独立的(包括 Gmail 和 Outlook)上不受支持。鉴于它们是最常见的电子邮件客户端,您不想提供对它们不起作用的解决方案,否则您的大多数用户都会不高兴。

IMO 你最好的选择是在服务器中托管图像并在你的 freemarker 模板中使用完全限定的 URL。

另一种方法是使用附件并在 html 源中引用它们,如下所述: 但它需要更改电子邮件的发送方式(需要添加附件)所以它可能不适合你的情况。