springboot怎么发送带样式的邮件
时间: 2023-07-08 15:42:20 浏览: 59
要发送带样式的邮件,可以使用Spring的JavaMailSender接口和Thymeleaf模板引擎来实现。
首先需要在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
然后在application.properties文件中添加邮件配置信息,例如:
```
spring.mail.host=smtp.qq.com
spring.mail.username=your_email@qq.com
spring.mail.password=your_email_password
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.qq.com
```
接下来创建一个邮件发送服务类MailService,其中sendHtmlMail方法用于发送HTML格式的邮件:
```
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
public void sendHtmlMail(String to, String subject, String content) throws Exception {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom("your_email@qq.com");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
}
public void sendTemplateMail(String to, String subject, Map<String, Object> params, String templateName) throws Exception {
Context context = new Context();
context.setVariables(params);
String content = templateEngine.process(templateName, context);
sendHtmlMail(to, subject, content);
}
}
```
其中sendTemplateMail方法用于使用Thymeleaf模板引擎来生成邮件内容。
最后创建一个Thymeleaf模板,例如:
```
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件标题</title>
</head>
<body>
<h1>邮件内容</h1>
<p th:text="${content}"></p>
</body>
</html>
```
可以看到,Thymeleaf模板中可以使用HTML标签和Thymeleaf的表达式语言来构造邮件内容。在Java代码中,需要使用sendTemplateMail方法来发送邮件,例如:
```
Map<String, Object> params = new HashMap<>();
params.put("content", "<b>这是一封带样式的邮件</b>");
mailService.sendTemplateMail("to_email@example.com", "邮件标题", params, "mail_template");
```
这样就可以发送带样式的邮件了。