Spring Boot mail

Spring Boot mail 入门实战

Posted by leone on 2017-11-18

Spring Boot mail

开发环境

开发工具:Intellij IDEA 2018.2.6

springboot: 2.0.7.RELEASE

jdk:1.8.0_192

maven: 3.6.0

spring-boot-mail

SpringBoot 有提供发送邮件的实现,整合也非常方便只需要引入 SpringBoot 整合mail 的 starter 就可以使用 JavaMailSender 封装好的api实现发送邮件的功能。本文使用了freemarker 和thymeleaf 两种模板引擎技术来实现发送模板类型的邮件。

pom:

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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<groupId>com.andy</groupId>
<artifactId>spring-boot-mail</artifactId>
<version>1.0.7.RELEASE</version>
<modelVersion>4.0.0</modelVersion>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.spring.platform</groupId>
<artifactId>platform-bom</artifactId>
<version>Cairo-SR6</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<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>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>

<!--生成二维码-->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>

</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>

<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.0.6.RELEASE</version>
<configuration>
<!--<mainClass>${start-class}</mainClass>-->
<layout>ZIP</layout>
</configuration>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
  • 启动类
1
2
3
4
5
6
7
8
9
10
11
12
13
14

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
* @author Leone
* @since 2018-05-09
**/
@SpringBootApplication
public class MailApplication {
public static void main(String[] args) {
SpringApplication.run(MailApplication.class, args);
}
}
  • freemarker 模板(ftlMail.ftl)
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
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div style="width: 600px; text-align: left; margin: 0 auto;">
<h3 style="color: #005da7;">您好!${(to)!""}</h3>
<div style="border-bottom: 5px solid #005da7; height: 2px; width: 100%;"></div>
<div style="border: 1px solid #005da7; font-size: 16px; line-height: 50px; padding: 20px;">
<div>
欢迎注册xxx!
</div>
<div style="border-bottom: 2px solid #005da7; height: 2px; width: 100%;"></div>
<div>点击链接激活您的账号!</div>
<div>
<span><a href="${(content)!""}">激活</a></span>
</div>
<div>
<img src="https://www.baidu.com/img/xinshouye_7c5789a51e2bfd441c7fe165691b31a1.png" alt="baidu"/>
</div>
<div>
想了解更多信息,请访问 <a href="https://www.baidu.com/">https://www.baidu.com/</a>
</div>
</div>
</div>
</body>
</html>
  • thymeleaf 模板(htmlMail.html)
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
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div style="width: 600px; text-align: left; margin: 0 auto;">
<h1>XXX</h1>
<div style="border-bottom: 5px solid #005da7; height: 2px; width: 100%;"></div>
<div style="border: 1px solid #005da7; font-size: 16px; line-height: 50px; padding: 20px;">
<div>
<p th:text="${to}+' 您好,欢迎注册xxx!!'"></p>
</div>
<div style="border-bottom: 2px solid #005da7; height: 2px; width: 100%;"></div>
<div>请点击下面链接激活您的账号!</div>
<div>
<span><a th:href="${content}">激活</a></span>
</div>
<div>
<img src="https://www.baidu.com/img/xinshouye_7c5789a51e2bfd441c7fe165691b31a1.png" alt="baidu"/>
</div>
<div>
想了解更多信息,请访问 <a href="https://www.baidu.com/">https://www.baidu.com/</a>
</div>
</div>
</div>
</body>
</html>
  • application.yml
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
server:
port: 8083
servlet:
path: /

spring:
application:
name: spring-boot-mail
http:
encoding:
charset: UTF-8
enabled: true
# JavaMailSender 邮件发送的配置 我使用的163邮箱作为发送方
mail:
host: smtp.163.com
username: xxx@163.com
password: xxx
properties:
mail:
smtp:
auth: true
starttls:
enabled: true
required: true
default-encoding: UTF-8


# thymeleaf 配置
thymeleaf:
cache: false
prefix: classpath:/templates/thymeleaf
suffix: .html
mode: HTML
encoding: UTF-8
servlet:
content-type: text/html
# freemarker配置
# freemarker:
# template-loader-path: classpath:/templates/freemarker/
# allow-request-override: false
# cache: false
# suffix: .ftl
# charset: UTF-8
# content-type: text/html
# check-template-location: true
# expose-request-attributes: false
# expose-session-attributes: false
# expose-spring-macro-helpers: false
  • MailService.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
package com.andy.mail.service;

import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
* @author Leone
* @since 2018-05-09
**/
@Slf4j
@Service
public class MailService {

@Value("${spring.mail.username}")
private String from;

@Autowired
private JavaMailSender javaMailSender;

@Autowired
private TemplateEngine templateEngine;

// @Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;

private static final Charset CHARSET = StandardCharsets.UTF_8;

private static final String THYMELEAF_TEMPLATE = "/htmlMail";

private static final String FREEMARKER_TEMPLATE = "ftlMail.ftl";

private static final String filePath = "hello.zip";


/**
* 发送freemarker模板mail
*
* @param to
* @param subject
* @return
* @throws Exception
*/
public boolean sendFreemarkerMail(String to, String subject, String content) {
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(from);
helper.setTo(InternetAddress.parse(to));
helper.setSubject("[" + subject + " " + LocalDate.now() + "]");
Map<String, Object> model = new HashMap<>();
model.put("subject", subject);
model.put("content", content);
model.put("to", to);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(FREEMARKER_TEMPLATE);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(text, true);
javaMailSender.send(mimeMessage);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
return false;
}
}

/**
* 发送thymeleaf邮件
*
* @param to
* @param subject
* @return
* @throws Exception
*/
public boolean sendThymeleafMail(String to, String subject, String content) {
// String token = storage(to);
String token = "xxx";
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, CHARSET.displayName());
Map<String, Object> map = new HashMap<>();
map.put(content, token);
map.put("content", content);
map.put("subject", subject);
map.put("to", to);
IContext context = new Context(Locale.CHINESE, map);
String process = templateEngine.process(THYMELEAF_TEMPLATE, context);
messageHelper.setFrom(from);
messageHelper.setTo(to);
messageHelper.setSubject("[" + subject + " " + LocalDate.now() + "]");
messageHelper.setText(process, true);
javaMailSender.send(mimeMessage);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
e.printStackTrace();
return false;
}
}


/**
* 发送文本邮件
*
* @param to
* @param subject
* @param content
*/
public boolean sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (Exception e) {
log.error("send mail filed:{}", e);
return false;
}
}

/**
* 发送带附件的邮件
*
* @param to
* @param subject
* @param content
*/
public boolean sendAttachmentsMail(String to, String subject, String content) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);

FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
//helper.addAttachment("test"+fileName, file);

javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (MessagingException e) {
log.error("send mail filed:{}", e);
return false;
}
}


/**
* 发送正文中有静态资源(图片)的邮件
*
* @param to
* @param subject
* @param content
* @param rscPath
* @param rscId
*/
public boolean sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
MimeMessage message = javaMailSender.createMimeMessage();

try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);

FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);

javaMailSender.send(message);
log.info("send mail success!");
return true;
} catch (MessagingException e) {
log.error("send mail filed:{}", e);
return false;
}
}

}
  • MailController.java
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.andy.mail.controller;


import com.andy.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
* @author Leone
* @since 2018-05-09
**/
@Slf4j
@Controller
@RequestMapping("/api/mail")
public class MailController {

@Autowired
private MailService mailService;

private static Map<String, Object> content = new HashMap<>();

static {
content.put("title", "标题");
content.put("content", "http://www.baidu.com");
content.put("to", "james@gmail.com");
}

@ResponseBody
@GetMapping("/send/ftl")
public String sendFtlMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendFreemarkerMail(to, subject, content);
return String.valueOf(flag);
}

@ResponseBody
@GetMapping("/send/html")
public String sendHtmlMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendThymeleafMail(to, subject, content);
return String.valueOf(flag);
}

@ResponseBody
@GetMapping("/send/simple")
public String sendSimpleMain(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendSimpleMail(to, subject, content);
return String.valueOf(flag);
}

@ResponseBody
@GetMapping("/send/htm")
public String sendAttachmentsMail(String to, String subject, String content, HttpServletRequest request) {
boolean flag = mailService.sendAttachmentsMail(to, subject, content);
return String.valueOf(flag);
}


@RequestMapping("/html")
public String helloHtml(Map<String, Object> map) {
map.putAll(content);
return "/htmlMail";
}

@RequestMapping("/ftl")
public String helloFtl(Map<String, Object> map) {
map.putAll(content);
return "ftlMail";
}

}

GitHub