简体   繁体   English

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

[英]Spring Boot - Can't add inline image using thymeleaf mail template

I'm trying to add an inline image in thymeleaf email html template like in tutorials, but nothings work.我正在尝试像在教程中那样在 thymeleaf 电子邮件 html 模板中添加内联图像,但没有任何效果。

This is my method from service class:这是我在服务类中的方法:

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 */);
}


And this is my thymeleaf HTML template: 这是我的 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>


All above the <img src=...> which is not appearing, works perfectly fine. 在未出现的<img src=...>之上,一切正常。

You need to initialize your message as a Multipart message like this:您需要像这样将消息初始化为多部分消息:

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

It is not sufficient to just set multipart to true .仅仅将 multipart 设置为true是不够的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM