java - Spring Boot - 无法使用 thymeleaf 邮件模板添加内联图像

标签 java spring spring-boot thymeleaf

我正在尝试像在教程中那样在 thymeleaf 电子邮件 html 模板中添加内联图像,但没有任何效果。

这是我在服务类中的方法:

public void sendOrderDetailsEmail(PortfolioModel model)  {  
        try {

          MimeMessage mimeMessage = mailSender.createMimeMessage();
          MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
          Context context = new Context();
          context.setVariable("portfolio", model);
          context.setVariable("products", model.getProducts());
          context.setVariable("logo", "logo");

          String htmlContent = templateEngine.process(ORDER_DETAILS_HTML, context);
          message.addInline("logo", new ClassPathResource("images/logo.png"), "image/png");

          LOG.info("Sending order configuration email to  " + model.getUser().email);
          configureMessage(message, model.getUser().email, "Order details", htmlContent);
          mailSender.send(mimeMessage);
        } catch (Exception e) {
            LOG.error(e);
        }
    }

private void configureMessage(MimeMessageHelper message, String to, String subject, String content) 
{
    message.setFrom(new InternetAddress("myemail@address.org", "info"));
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content, true /* is html */);
}


这是我的 thymeleaf HTML 模板:

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://thymeleaf.org">
<head>
</head>
<body>
<p>
    <img src="logo.png" th:src="|cid:${logo}|" />
</p>
<div th:object="${portfolio}">
    <p><span th:utext="${portfolio.user.fullname}"></span></p>
    <p><b>Your order id: </b><span th:utext="${portfolio.orderId}"></span></p>
    <p><b>Order information:</b></p>
   <div th:if="${products} != null">
       <table>
         <tr th:each="product : ${products}">
             - Product:
            <td th:text="${product.model}"></td >
            <td th:text="${product.year}"></td >
            <td th:text="${product.color}"></td >
        </tr>
       </table>
    </div>
</div>
</body>
</html>


所有在<img src=...>之上没有出现,工作得很好。

最佳答案

您需要像这样将消息初始化为多部分消息:

final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED, "UTF-8"); // true = multipart

仅仅将 multipart 设置为 true 是不够的。

关于java - Spring Boot - 无法使用 thymeleaf 邮件模板添加内联图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59862240/

相关文章:

java - 条件断点错误 - 类型未实现选择器最大值和签名

java - 如何在 Struts 2 中处理表单上的索引属性按钮

sql-server - Spring 批处理 "Invalid object name BATCH_JOB_INSTANCE"

java - Spring3 的 Google 日历 API 库?

spring-boot - 如何使用 Springdoc Open API 3 规范在 OAuth2 隐式流的 header 中添加 "Authorization : Bearer <token>"

java - 从 Spring 应用程序连接到 Cassandra 池的问题

java - JPA getResultList() 为 MySQL 返回 BigInteger 但为 Microsoft SQL Server 返回 Integer

java - Hibernate 不生成 id

带有 tomcat 和 cxf-servlet 的 spring-boot

spring-mvc - 在spring mvc 3中,如何在返回ModelAndView的同时编写cookie?