Spring Boot发送HTML邮件时如何设置模板?
在Spring Boot中,你可以使用Thymeleaf
作为模板引擎来发送HTML邮件。首先,确保你的pom.xml
中包含了spring-boot-starter-mail
和thymeleaf-spring5
依赖。
<dependencies>
<!-- Spring Boot Mail Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- Thymeleaf Template Engine -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
然后,在application.properties
或application.yml
中配置你的邮件服务器信息。
spring.mail.host=smtp.example.com
spring.mail.port=587
spring.mail.username=your_username
spring.mail.password=your_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
接下来,创建一个服务来发送邮件,并使用Thymeleaf渲染模板。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.internet.MimeMessage;
@Service
public class EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
public void sendHtmlEmail(String to, String subject, Map<String, Object> variables, String templateName) {
try {
// Create the message
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setTo(to);
helper.setSubject(subject);
// Create the context for the template
Context context = new Context();
for (Map.Entry<String, Object> entry : variables.entrySet()) {
context.setVariable(entry.getKey(), entry.getValue());
}
// Process the template
String process = templateEngine.process(templateName, context);
helper.setText(process, true);
// Send the email
mailSender.send(mimeMessage);
评论已关闭