java - 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 */);
}
这是我的百里香 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=...>
没有出现的,工作得很好。
解决方案
您需要将消息初始化为 Multipart 消息,如下所示:
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, MimeMessageHelper.MULTIPART_MODE_MIXED, "UTF-8"); // true = multipart
仅将 multipart 设置为 是不够的true
。
推荐阅读
- java - Microsoft Outlook API - 401 令牌授权
- java - 如果Java中的另一个标签内有其他同名标签,如何提取XML文件中的特定标签内容?
- c# - Azure 应用服务容器上的 ASP.net 核心 docker https
- php - Laravel:如何使用 select2.js 更新多个 Select 选项
- c++ - std::tuple 和移动语义
- python - 分配之前引用的局部变量“post” - 烧瓶
- php - Laravel 5.4 如何获取与类别相关的文章
- python - 在 Tkinter 标签文本的末尾显示三个点
- postgresql - PostgreSQL 对别名有任何保护吗?
- regex - excel vba 正则表达式模式精确字符串匹配