在项目的维护过程中,我们通常会在应用中加入短信或者邮件预警功能,比如当应用出现异常宕机时应该及时地将预警信息发送给运维或者开发人员,本文将介绍如何在Spring Boot中发送邮件。在Spring Boot中发送邮件使用的是Spring提供的org.springframework.mail.javamail.JavaMailSender,其提供了许多简单易用的方法,可发送简单的邮件、HTML格式的邮件、带附件的邮件,并且可以创建邮件模板。
引入依赖
在Spring Boot中发送邮件,需要用到spring-boot-starter-mail,引入spring-boot-starter-mail:
1 | <dependency> |
邮件配置
在application.yml中进行简单的配置(以163邮件为例):
1 | server: |
spring.mail.username,spring.mail.password填写自己的邮箱账号密码即可。
发送简单的邮件
编写EmailController,注入JavaMailSender:
1 | import org.springframework.beans.factory.annotation.Autowired; |
启动项目访问http://localhost/email/sendSimpleEmail,提示发送成功:

发送HTML格式的邮件
改造EmailController,SimpleMailMessage替换为MimeMessage:
1 | import javax.mail.internet.MimeMessage; |
helper.setText(sb.toString(), true);中的true表示发送HTML格式邮件。启动项目,访问http://localhost/email/sendHtmlEmail,提示发送成功,可看到文本已经加上了颜色#6db33f:

发送带附件的邮件
发送带附件的邮件和普通邮件相比,其实就只是多了个传入附件的过程。不过使用的仍是MimeMessage:
1 | package com.springboot.demo.controller; |
启动项目访问http://localhost/email/sendAttachmentsMail,提示发送成功:

发送带静态资源的邮件
发送带静态资源的邮件其实就是在发送HTML邮件的基础上嵌入静态资源(比如图片),嵌入静态资源的过程和传入附件类似,唯一的区别在于需要标识资源的cid:
1 | package com.springboot.demo.controller; |
helper.addInline("img", file);中的img和图片标签里cid后的名称相对应。启动项目访问http://localhost/email/sendInlineMail,提示发送成功:

使用模板发送邮件
在发送验证码等情况下可以创建一个邮件的模板,唯一的变量为验证码。这个例子中使用的模板解析引擎为Thymeleaf,所以首先引入Thymeleaf依赖:
1 | <dependency> |
在template目录下创建一个emailTemplate.html模板:
1 |
|
发送模板邮件,本质上还是发送HTML邮件,只不过多了绑定变量的过程,详细如下所示:
1 | package com.springboot.demo.controller; |
其中code对应模板里的${code}变量。启动项目,访问http://localhost/email/sendTemplateEmail?code=EOS9,页面提示发送成功:

源码链接:https://github.com/wuyouzhuguli/Spring-Boot-Demos/tree/master/22.Spring-Boot-Email

