springboot使用freemarker发送模板邮件

springboot使用freemarker发送模板邮件

1、引入mail和freemarker模块依赖

1
2
3
4
5
6
7
8
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

2、在配置文件中配置信息

1
2
3
4
5
6
7
8
spring:
mail:
default-encoding: utf-8
host: smtp.126.com
password: xxxxxxx
port: 25
protocol: smtp
username: xxxxx@126.com

3、在resources/templates下新建模板welcome.ftl

1
2
3
4
5
6
<!DOCTYPE html>
<html>
<body>
<h4>${UserName},你好!</h4>
</body>
</html>

4、使用模板测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@Autowired 
private Configuration configuration;

@Autowired
private JavaMailSender jms;

@Test
public void send(){
MimeMessage message =jms.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper( message,true);
helper.setFrom("xxxx@126.com");
helper.setTo("xxxx@qq.com");
helper.setSubject("使用模板");

Map<String, Object> model = new HashMap();
model.put("UserName", "yao");

try {
Template template = configuration.getTemplate("welcome.ftl");
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);

helper.setText(html,true);
} catch (Exception e) {
e.printStackTrace();
}


} catch (MessagingException e) {
e.printStackTrace();
}

jms.send(message);
}

-------------本文结束感谢您的阅读-------------