【问题标题】:How to add image to a Freemarker template with JavaMail如何使用 JavaMail 将图像添加到 Freemarker 模板
【发布时间】:2019-02-01 12:50:18
【问题描述】:

在这个问题被标记为重复之前, Add image to freemarker template for mail?

这个问题没有为我的问题提供解决方案。 所以我想在 Freemarker HTML 模板中添加图像作为背景,我将其附加到 Java 中的 Google Gmail API 程序。

这是 Freemarker 的代码:-

<style>
    body{
background-image: url("cid:${image.jpg}");
}
     .container {
              position: absolute;
              padding:25px;
              margin:25px;
              border:5px;
              text-align: justify;
              text-justify: inter-word;
              font-family: "Times New Roman";
              font-style: italic;
            }
 </style>

我使用 Google Gmail API 插入图片的方式是:-

Multipart multipart = new MimeMultipart();
    MimeBodyPart bodyPart = new MimeBodyPart();
    Template t = freemarkerTemlate.getTemplate("OneEmployee.ftl");
    String mailContent = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);
    bodyPart.setContent(mailContent, "text/html");
    multipart.addBodyPart(bodyPart);

    DataSource fds = new FileDataSource(Mailer.class.getClassLoader().getResource("images/image1.jpg").getFile());
    bodyPart = new MimeBodyPart();
    bodyPart.setDataHandler(new DataHandler(fds));
    bodyPart.setHeader("Content-ID", "<image.jpg>");
    multipart.addBodyPart(bodyPart);

我的图像在包含另一个图像目录的资源目录中

现在我已经尝试了几乎所有可能的代码变体,例如使用

<img src="">

在 ${} 中添加 cid: 并且不使用“”,但无论如何它似乎都没有设置图像。

在某些情况下,它会在不附加图像的情况下运行,在某些情况下,它会运行但也会在控制台上引发错误:-

Application failed at {image1.jpg}:- Missing or Null Argument 

我使用的模型是:-

 Map model = new HashMap();
 model.put("emailNames", emailNames);

我没有在模型中添加任何其他内容,因为这是除了我要插入到 freemarker 模板中的图像之外的唯一其他内容

我做错了什么或错过了什么?

编辑 2

我还尝试通过将图像设置为键来通过模型插入图像 代码已附上供参考

Map model = new HashMap();
 model.put("emailNames", emailNames);
 model.put("image.jpg", Mailer.class.getClassLoader().getResource("images/image1.jpg").getFile())

还是不行!

编辑 2

有趣的是,我注意到当我没有定义 cid 时,它确实将背景图像添加为附件,但每当我添加 cid 语法时,它不会添加为附件,而是简单地忽略邮件。

我在网上读到,根据教程,您不会将要插入的图像作为模型的一部分传递,而是将其添加为定义图像的 content_id (cid) 的附件。

谢谢

【问题讨论】:

  • 你能分享一下model你是怎么设置的吗?在模型中你是否设置了image1.jpg 作为key?
  • 不,先生,我还没有将 image1 设置为模型中的键,我还在附加模型
  • 那么${image.jpg}这部分是错误的。您可以在model中设置图片路径并发送到ftl
  • 您希望url("cid:${image.jpg}") 做什么?该错误表明这在 freemarker 中出错了,甚至在您必须处理正确引用图像的潜在问题以便它实际工作之前。
  • @MarkRotteveel OP 不会在模型上发送任何内容。当您访问任何属性时,显然将为 null。

标签: java spring spring-data jakarta-mail freemarker


【解决方案1】:

所以我终于能够得到解决方案的答案

我从资源中的图像文件夹加载图像的方式是错误的

File file = new ClassPathResource("image").getFile();

这就是这样做的方法 将其传递给 Freemarker 模板时,您只需执行 cid:imageURL 即可,它应该可以工作。

您还应该关注@Bill Shannon 和@Mark Rotteveel 的评论

【讨论】:

    猜你喜欢
    • 2012-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多