SpringBoot中使用Thymeleaf发送带数据与Logo的模板邮件问题
用Thymeleaf发送带数据和Logo的邮件完整实现方案
嘿,我来帮你把这个功能补全,搞定Thymeleaf邮件里的数据展示和Logo嵌入的问题!下面是完整的实现步骤和代码:
1. 补全邮件发送函数
先把你没写完的sendingemailtest方法补全,这里包含了模板渲染、图片嵌入的核心逻辑:
public void sendingemailtest() throws MessagingException, IOException { String recipientName = "Hero"; String recipientEmail = "hero@example.com"; // 替换成实际收件人邮箱 final Context context = new Context(); final MimeMessage mimeMessage = this.mailSenderTest.createMimeMessage(); final MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // 1. 设置邮件基础信息 helper.setTo(recipientEmail); helper.setSubject("来自Thymeleaf的测试邮件"); helper.setFrom("your-email@example.com"); // 替换成发件人邮箱 // 2. 给Thymeleaf模板传递数据 context.setVariable("name", recipientName); // 可添加更多自定义数据,比如订单号、日期 context.setVariable("orderId", "ORD-2024-001"); context.setVariable("sendDate", LocalDate.now().toString()); // 3. 渲染Thymeleaf模板 String emailContent = templateEngine.process("email-template", context); helper.setText(emailContent, true); // 第二个参数true表示发送HTML邮件 // 4. 嵌入Logo图片(图片需放在项目的resources/static/images目录下) ClassPathResource logoResource = new ClassPathResource("static/images/company-logo.png"); helper.addInline("companyLogo", logoResource, "image/png"); // 5. 发送邮件 mailSenderTest.send(mimeMessage); }
2. 编写Thymeleaf邮件模板
在resources/templates目录下创建email-template.html,这里展示如何使用变量和嵌入图片:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>测试邮件</title> <style> .email-container { width: 80%; margin: 0 auto; font-family: Arial, sans-serif; } .logo { width: 150px; margin-bottom: 20px; } .greeting { font-size: 18px; color: #333; } </style> </head> <body> <div class="email-container"> <!-- 嵌入Logo图片,th:src对应Java代码里addInline的第一个参数 --> <img th:src="'cid:companyLogo'" alt="公司Logo" class="logo"> <!-- 展示传递的变量 --> <p class="greeting">嗨,<span th:text="${name}"></span>!</p> <p>这是你的测试邮件,你的订单号是:<strong th:text="${orderId}"></strong></p> <p>邮件发送日期:<span th:text="${sendDate}"></span></p> <p>感谢你的使用!</p> </div> </body> </html>
3. 关键注意事项
- 依赖检查:确保项目已引入Spring Mail和Thymeleaf的依赖(Spring Boot项目可直接用starter):
<!-- Spring Boot Mail Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- Thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> - 图片路径:嵌入的图片要放在
src/main/resources/static/images目录下,或根据项目资源配置调整路径,确保ClassPathResource能正确读取。 - HTML邮件开关:调用
helper.setText(emailContent, true)时,第二个参数必须设为true,否则HTML标签会被当作纯文本显示。 - 编码设置:
MimeMessageHelper构造器里指定UTF-8,避免中文乱码问题。
这样你就能成功发送带动态数据和Logo的HTML邮件啦!
内容的提问来源于stack exchange,提问作者msf6012
相关产品推荐
相关产品推荐

