现在发送邮件是一个网站必备的功能,比如注册激活,或者忘记密码等等都需要发送邮件。正常我们会用JavaMail相关api来写发送邮件的相关代码,但现在springboot提供了一套更简易使用的封装。也就是我们使用SpringBoot来发送邮件的话,代码就简单许多,毕竟SpringBoot是开箱即用的 ,它提供了什么,我们了解之后觉得可行,就使用它,自己没必要再写原生的。

导入依赖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>

配置发送方信息

我们需要在SpringBoot配置文件(application.yml)中配置发送方的信息,包括以下信息:

用户名:也就是我们的邮箱账号
密码:我们刚刚生成的授权码
邮箱主机:配置使用哪个邮箱服务器发送邮件
还有等等其他可选配置,在下面配置代码中,大家需要填写自己的用户名、密码、from(和用户名一样)。

spring:
  mail:
    host: mail.xxxx.com
    #发送邮件的邮箱地址
    username: hadoop
    #客户端授权码,不是邮箱密码,这个在qq邮箱设置里面自动生成的
    password: a5ve
    properties.mail.smtp.port: 587 #端口号465或587
    from: hadoop@xxx.com  # 发送邮件的地址,和上面username一致
    default-encoding: utf-8
    # 收件人 这个是自定义的
    to: xxx@xxx.com, op@xxx.com

MailDO

public class MailDO {
    private String title;
    private String content;
     * 接收人邮箱
    private String[] email;
     * 附加,value 文件的绝对地址/动态模板数据
    private Map<String, Object> attachment;
    public String getTitle() {
        return title;
    public void setTitle(String title) {
        this.title = title;
    public String getContent() {
        return content;
    public void setContent(String content) {
        this.content = content;
    public String[] getEmail() {
        return email;
    public void setEmail(String[] email) {
        this.email = email;
    public Map<String, Object> getAttachment() {
        return attachment;
    public void setAttachment(Map<String, Object> attachment) {
        this.attachment = attachment;
    @Override
    public String toString() {
        return "MailDO{" +
                "title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", email=" + Arrays.toString(email) +
                ", attachment=" + attachment +
                '}';

EmailService

我们需要自己封装邮件服务,这个服务只是便于Controller层调用,也就是根据客户端发送的请求来调用,封装三种邮件服务

  • 发送普通文本邮件
  • 发送HTML邮件:一般在注册激活时使用
  • 发送带附件的邮件:可以发送图片等等附件
public interface EmailService {
     * @param mailDO
    void sendTextMail(MailDO mailDO);
     * 发送html邮件
     * @param mailDO
     * @param isShowHtml
    void sendHtmlMail(MailDO mailDO,boolean isShowHtml);
     * 发送Template邮件
     * @param mailDO
    void sendTemplateMail(MailDO mailDO);

EmailServiceImpl

@Service
public class EmailServiceImpl implements EmailService {
    private final static Logger log = LoggerFactory.getLogger(EmailServiceImpl.class);
    //template模板引擎
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private JavaMailSender javaMailSender;
    @Value("${spring.mail.from}")
    private String from;
     * 纯文本邮件
     * @param mail
    @Async
    @Override
    public void sendTextMail(MailDO mail){
        //建立邮件消息
        SimpleMailMessage message = new SimpleMailMessage();
        // 发送人的邮箱
        message.setFrom(from);
        message.setSubject(mail.getTitle());
        //发给谁  对方邮箱
        message.setTo(mail.getEmail());
        message.setText(mail.getContent());
        try {
            javaMailSender.send(message);
        } catch (MailException e) {
            log.error("纯文本邮件发送失败->message:{}",e.getMessage());
            throw new RuntimeException("邮件发送失败");
     * 发送的邮件是富文本(附件,图片,html等)
     * @param mailDO
     * @param isShowHtml 是否解析html
    @Async
    @Override
    public void sendHtmlMail(MailDO mailDO, boolean isShowHtml) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //是否发送的邮件是富文本(附件,图片,html等)
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            messageHelper.setFrom(from);// 发送人的邮箱
            messageHelper.setTo(mailDO.getEmail());//发给谁  对方邮箱
            messageHelper.setSubject(mailDO.getTitle());//标题
            messageHelper.setText(mailDO.getContent(),isShowHtml);//false,显示原始html代码,无效果
            //判断是否有附加图片等
            if(mailDO.getAttachment() != null && mailDO.getAttachment().size() > 0){
                mailDO.getAttachment().entrySet().stream().forEach(entrySet -> {
                    try {
                        File file = new File(String.valueOf(entrySet.getValue()));
                        if(file.exists()){
                            messageHelper.addAttachment(entrySet.getKey(), new FileSystemResource(file));
                    } catch (MessagingException e) {
                        log.error("附件发送失败->message:{}",e.getMessage());
                        throw new RuntimeException("附件发送失败");
                });
            javaMailSender.send(mimeMessage);
            log.info("富文本邮件发送成功,from: {}, to: {}",from,mailDO.getEmail());
        } catch (MessagingException e) {
            log.error("富文本邮件发送失败->message:{}",e.getMessage());
            throw new RuntimeException("邮件发送失败");
     * 发送模板邮件 使用thymeleaf模板
     * 若果使用freemarker模板
     *     Configuration configuration = new Configuration(Configuration.VERSION_2_3_28);
     *     configuration.setClassForTemplateLoading(this.getClass(), "/templates");
     *     String emailContent = FreeMarkerTemplateUtils.processTemplateIntoString(configuration.getTemplate("mail.ftl"), params);
     * @param mailDO
    @Async
    @Override
    public void sendTemplateMail(MailDO mailDO) {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage,true);
            // 发送人的邮箱
            messageHelper.setFrom(from);
            //发给谁  对方邮箱
            messageHelper.setTo(mailDO.getEmail());
            messageHelper.setSubject(mailDO.getTitle());
            //使用模板thymeleaf
            //Context是导这个包import org.thymeleaf.context.Context;
            Context context = new Context();
            //定义模板数据
            context.setVariables(mailDO.getAttachment());
            //获取thymeleaf的html模板
            String emailContent = templateEngine.process("indexPatternMail.html",context); //指定模板路径
            messageHelper.setText(emailContent,true);
            //发送邮件
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("模板邮件发送失败->message:{}",e.getMessage());
            throw new RuntimeException("邮件发送失败");

模板 mail.html

放在templates/mail目录下

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
    <meta charset="UTF-8">
    <title>title</title>
</head>
    <h3>你看我<span style="font-size: 35px" th:text="${username}"></span>, 哈哈哈!</h3>
</body>
</html>