java - 如何使用 ThymeLeaf 发送带有内联图像的电子邮件

标签 java thymeleaf

我正在尝试使用 ThymeLeaf 和 Spring 发送带有内联图像的电子邮件,但到目前为止没有成功。电子邮件已发送,但内联图像不会显示在电子邮件中。

该项目不是基于网络的(不是网站),而是桌面独立的,不是移动的

这是我获取图像文件的方式:

URL url = getClass().getResource("/LawFirmAdvisoryGroup.jpg");
File file = new File(url.getPath());

MultipartFile multipartFile = new MockMultipartFile(file.getName(),
    file.getName(), "image/jpeg", IOUtils.toByteArray(input));

我的服务类:

@Autowired
private JavaMailSender mailSender;

@Autowired
private TemplateEngine templateEngine;

public void sendMailWithInline(final String recipientName, final String recipientEmail, final MultipartFile image, final byte[] imageBytes)
throws MessagingException {

    final Context ctx = new Context();
        ctx.setVariable("imageResourceName", image.getName()); // so that we can reference it from HTML

        final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
        final MimeMessageHelper message
        = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setSubject("Inline Image");
        message.setFrom("XXXX@yahoo.com");
        message.setTo(recipientEmail);

        // Add the inline image, referenced from the HTML code as "cid:${imageResourceName}"
        final InputStreamSource imageSource = new ByteArrayResource(imageBytes);
        message.addInline(image.getName(), imageSource, image.getContentType());


        final String htmlContent = this.templateEngine.process("left_sidebar.html", ctx);
        message.setText(htmlContent, true);
        this.mailSender.send(mimeMessage);

    }

HTML:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title th:remove="all">Email with inline image</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  </head>
  <body>
    <p>
      <img src="LawFirmAdvisoryGroup.jpg" th:src="'cid:' + ${imageResourceName}" />
    </p>
  </body>
</html>

最佳答案

只需将对 setText() 的调用向上移动几行即可。

MimeMessageHelper.addInLine() 的 javadoc说:

NOTE: Invoke addInline after setText(java.lang.String); else, mail readers might not be able to resolve inline references correctly.

关于java - 如何使用 ThymeLeaf 发送带有内联图像的电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32140262/

相关文章:

java - 使用循环数组实现双端队列?

java - 尝试解析时间

java - Spring Security - 公共(public)页面重定向到使用无效 session ID 登录

java - 表单提交发送不需要的 GET 请求

javascript - 我怎样才能通过thymeleaf th :replace?传递这个字符串

java - 无法使用 Java 9 在 Eclipse 上运行 junit 测试

java - 在 Jfreechart 中自定义鼠标光标

spring-boot - Thymeleaf 如何查看当前 URL?

javascript - Thymeleaf:在 Javascript 中使用带有 'th:href' 的链接

java - "No message available"使用 Spring Boot/Thymeleaf