邮件服务在很多项目中都非常常见,比如注册激活邮件,密码找回邮件。在Spring Boot中,我们可以很方便的集成邮件服务,只需要添加支撑邮件服务的模块即可。接下来就用一个简单的demo演示Spring Boot项目中如何集成邮件服务。
1.添加依赖
<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>
2.实现邮件服务步骤
在Spring Boot项目中使用邮件服务就是实现可以不用登陆邮箱可以给另一个邮箱发送邮件。一般在邮件服务中主要有发件人,邮件本身,收件人等角色;邮件一般包括主题、收件人、抄送、正文、附件等。所以,在Spring Boot项目中实现邮件服务的流程是将邮件发送给远程邮件服务器,接着由远程服务器将邮件推送到收件者邮箱中。
作为邮件发送方,我们需要一个第三方的邮箱服务器平台,这里我们选择网易163 邮箱作为发送方。此时,需要将 IMAP/SMTP 服务和 POP3/SMTP 服务打开,这里按照它的流程简单做完之后会生成一个授权码,它提示的授权码只会出现一次,所以需要将这个授权码做好备份。开启这个主要是为了让这个邮件服务器能够发现我们的客户端,进而接收我们发送的邮件并推送给接收放。
 接下来获取授权码:按照指示步骤操作即可。  我们在 pom.xml 文件中引入了核心的依赖模块spring-boot-starter-mail,该模块提供给我们了一个核心的抽象接口 MailSender。
public interface MailSender {
void send(SimpleMailMessage var1) throws MailException;
void send(SimpleMailMessage... var1) throws MailException;
}
在这里面定义了两个 send 方法,用于发送邮件给远程的邮箱服务器,而且我们看到每个邮件被封装为了 SimpleMailMessage 类,这个类是简单邮件类,它实现了 MailMessage 接口。
public interface MailMessage {
void setFrom(String var1) throws MailParseException;
void setReplyTo(String var1) throws MailParseException;
void setTo(String var1) throws MailParseException;
void setTo(String... var1) throws MailParseException;
void setCc(String var1) throws MailParseException;
void setCc(String... var1) throws MailParseException;
void setBcc(String var1) throws MailParseException;
void setBcc(String... var1) throws MailParseException;
void setSentDate(Date var1) throws MailParseException;
void setSubject(String var1) throws MailParseException;
void setText(String var1) throws MailParseException;
}
3. 具体实现
3.1 项目配置
spring:
mail:
host: smtp.163.com
#默认端口号465
port: 465
username: 你的邮箱用户名账号@163.com
password: 你的授权码
protocol: smtp
test-connection: true
default-encoding: UTF-8
properties:
mail.smtp.auth: true
mail.smtp.starttls.enable: true
mail.smtp.starttls.required: true
mail.smtp.ssl.enable: true
mail.display.sendmail: spring-boot-demo
3.2 创建MailService.java类及其实现类
public interface MailService {
void sendSimpleMail(String to, String subject, String content, String... cc);
void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException;
void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException;
void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException;
}
编写实现类。
@Service
public class MailServiceImpl implements MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendSimpleMail(String to, String subject, String content, String... cc) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
if (ArrayUtil.isNotEmpty(cc)) {
message.setCc(cc);
}
mailSender.send(message);
}
@Override
public void sendHtmlMail(String to, String subject, String content, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
mailSender.send(message);
}
@Override
public void sendAttachmentsMail(String to, String subject, String content, String filePath, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
helper.addAttachment(fileName, file);
mailSender.send(message);
}
@Override
public void sendResourceMail(String to, String subject, String content, String rscPath, String rscId, String... cc) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
if (ArrayUtil.isNotEmpty(cc)) {
helper.setCc(cc);
}
FileSystemResource res = new FileSystemResource(new File(rscPath));
helper.addInline(rscId, res);
mailSender.send(message);
}
}
普通文本类的邮件的发送封装的是 SimpleMailMessage 对象,其他几种类型的邮件的发送都是使用的 MimeMessage 这个对象,而且在发送之前在 MimeMessage 这个的基础上再封装了一层 MimeMessageHelper,利用这个 Helper 来进行邮件的 From、To 等这些属性的封装以及最后邮件的发送。
3.3 添加控制器
3.3.1 发送简单邮件
@Controller
public class EmailController {
@Autowired
private MailService mailService;
@GetMapping("/testSendSimpleMail")
@ResponseBody
public String sendSimpleMail() {
mailService.sendSimpleMail("接收方邮箱@qq.com", "这是一封简单邮件", "这是一封普通的SpringBoot测试邮件");
return "ok";
}
}
测试效果:  
3.3.2 发送html邮件
@Autowired
private TemplateEngine templateEngine;
@GetMapping("/sendHtmlMail")
@ResponseBody
public String sendHtmlMail() throws MessagingException {
Context context = new Context();
context.setVariable("project", "Spring Boot email");
context.setVariable("author", "picacho");
context.setVariable("url", "www.picacho.top");
String emailTemplate = templateEngine.process("welcome", context);
mailService.sendHtmlMail("接收方邮箱@qq.com", "这是一封模板HTML邮件", emailTemplate);
return "ok";
}
welcome.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>SpringBootEmail</title>
<style>
body {
text-align: center;
margin-left: auto;
margin-right: auto;
}
#welcome {
text-align: center;
}
</style>
</head>
<body>
<div id="welcome">
<h3>
欢迎使用 <span th:text="${project}"></span> - Powered By
<span th:text=" ${author}"></span>
</h3>
<span th:text="${url}"></span>
<div style="text-align: center; padding: 10px">
<a
style="text-decoration: none;"
href="#"
th:href="@{${url}}"
target="_bank"
>
<strong>spring-boot-demo,入门Spring Boot的首选Demo!:)</strong>
</a>
</div>
<div style="text-align: center; padding: 4px">
如果对你有帮助,点个赞吧!
</div>
</div>
</body>
</html>
emplateEngine 模板引擎调用它的 process 方法的时候就会去我们的模板默认模板路径下面去找这个文件,并根据 Context 对象设置的几个 variable 变量对应着模板中的内容去填充模版。
测试效果:  
3.3.3 发送带附件的邮件
@GetMapping("/sendAttachmentsMail")
@ResponseBody
public String sendAttachmentsMail() throws MessagingException {
URL resource = ResourceUtil.getResource("static/1.png");
System.out.println(resource.getPath());
mailService.sendAttachmentsMail("接收方邮箱@qq.com", "这是一封带附件的邮件", "邮件中有附件,请注意查收!", resource.getPath());
return "ok";
}
测试效果:  
3.3.4 发送自定义模版的html邮件
@GetMapping("/sendHtmlMail2")
@ResponseBody
public String sendHtmlMail2() throws MessagingException {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(context);
templateResolver.setCacheable(false);
templateResolver.setPrefix("classpath:/email/");
templateResolver.setSuffix(".html");
templateEngine.setTemplateResolver(templateResolver);
Context context = new Context();
context.setVariable("project", "Spring Boot email");
context.setVariable("author", "picacho");
context.setVariable("url", "www.picacho.top");
String emailTemplate = templateEngine.process("index", context);
mailService.sendHtmlMail("接收方邮箱@qq.com", "这是一封模板HTML邮件", emailTemplate);
return "ok";
}
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>SpringBootEmail</title>
<style>
body {
text-align: center;
margin-left: auto;
margin-right: auto;
}
#welcome {
text-align: center;
}
</style>
</head>
<body>
<div id="welcome">
<h3>
欢迎使用 <span th:text="${project}"></span> - Powered By
<span th:text=" ${author}"></span>
</h3>
<span th:text="${url}"></span>
<div style="text-align: center; padding: 10px">
<a
style="text-decoration: none;"
href="#"
th:href="@{${url}}"
target="_bank"
>
<strong>spring-boot-email</strong>
</a>
</div>
<div style="text-align: center; padding: 4px">
如果对你有帮助,请点个赞吧!
</div>
</div>
</body>
</html>
测试效果:  
3.3.5 发送静态资源邮件
@GetMapping("/sendResourceMail")
@ResponseBody
public String sendResourceMail() throws MessagingException {
String rscId = "picacho";
String content = "<html><body>这是带静态资源的邮件<br/><img src=\'cid:" + rscId + "\' ></body></html>";
URL resource = ResourceUtil.getResource("static/1.png");
mailService.sendResourceMail("接收方邮箱6@qq.com", "这是一封带静态资源的邮件", content, resource.getPath(), rscId);
return "ok";
}
测试效果:   源码下载地址:源码下载
|