SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送

SpringBoot2.x系列教程69--SpringBoot中整合邮件发送

作者:一一哥

注:
本文案例以QQ邮箱发送的实现为例!

一. 邮件发送概述

1. 概述

在Spring框架中提供了一个JavaMailSender接口,可以实现发送邮件功能。

而在Spring Boot中提供了一个对应的spring-boot-starter-mail依赖,添加该依赖后,Spring Boot将创建一个默认的JavaMailSender,该sender可以通过spring.mail命名空间下的配置项进一步自定义。

2. 发送邮件的场景

  • 用户通过邮件注册激活;
  • 通过邮件找回密码;
  • 通过邮件发送系统情况;
  • 通过邮件发送报表信息等。

3. 常用邮箱系统提供商

126邮箱SMTP服务器地址:smtp.126.com,端口号:465或者994

163邮箱SMTP服务器地址:smtp.163.com,端口号:465或者994

qq邮箱SMTP服务器地址:smtp.qq.com,端口号:465或587

yeah邮箱SMTP服务器地址:smtp.yeah.net,端口号:465或者994

4. QQ邮箱开启SMTP功能

为了保障用户邮箱的安全,QQ邮箱设置了POP3/SMTP/IMAP的开关。系统默认情况下相关设置是“关闭”状态的,在用户需要这些功能时请先“开启”,才可以用客户端软件收发邮件。

QQ邮箱开启SMTP功能步骤

默认情况下,SMTP服务器功能没有开启,所以需要在“设置”-->"账号"-->"POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务"中对SMTP进行开启。

SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第1张图片

可以看到默认情况下并没有开启SMTP服务。
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第2张图片

点击开启按钮就可以了,但是前提条件是你QQ邮箱绑定了手机号码,因为开启时需要发送短信验证码。
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第3张图片

开启成功后,会有一个授权码,这个授权码就是我们进行邮件发送时的邮箱密码,可以把它记住,不记也可以。因为这个授权码可以多次生成,只要用的时候发一次短信验证码,就可以得到一个新的授权码了。
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第4张图片

关于126或者163邮箱授权码的获取过程,与QQ类似,不一一列举。

二. Spring Boot整合邮件发送实现步骤

1. 创建web项目

我们按照之前的经验,创建一个web程序,并将之改造成Spring Boot项目,具体过程略。

2. 添加依赖包


    org.springframework.boot
    spring-boot-starter-mail



    org.springframework.boot
    spring-boot-starter-freemarker

3. 创建application.yml配置文件

spring:
  #freemarker模板配置
  freemarker:
    template-loader-path: classpath:/templates/
   #spring.freemarker.prefix=
    suffix: .ftl
    cache: false
    charset: utf-8
    check-template-location: true
    content-type: text/html
  #邮件配置  
  mail:
    host: smtp.qq.com
    from: [email protected]
    username: [email protected]
    #这里要替换成自己的邮箱授权码
    password: xxxxxx
    protocol: smtp
    default-encoding: UTF-8
    #以下可以不配置
    properties:
      mail:
        smtp:
          auth: true
        starttls:
          enable: true
          required: true

QQ邮箱配置

## QQ邮箱配置
spring:
  mail:
    host: smtp.qq.com #发送邮件服务器
    username: [email protected] #发送邮件的邮箱地址
    password:  xxx #客户端授权码,不是邮箱密码,在qq邮箱设置里面自动生成
    from: [email protected] # 发送邮件的地址,和上面username一致
    protocol: smtp
    default-encoding: UTF-8
    #以下可以配置或者不配置
    properties:
      mail:
        smtp:
          port: 465 #端口号465或587
          auth: true
        starttls:
          enable: true
          required: true

网易(126/163/yeah)邮箱配置

spring:
  mail:
    host: smtp.126.com #发送邮件服务器
    username: [email protected] #发送邮件的邮箱地址
    password: xxxxxxx #客户端授权码,不是邮箱密码,网易的是自己设置的
    properties.mail.smtp.port: 994 #465或者994
    from: [email protected] # 发送邮件的地址,和上面username一致
    default-encoding: UTF-8
    #以下可以配置或者不配置
    properties:
      mail:
        smtp:
          port: 465 #端口号465或994
          auth: true
        starttls:
          enable: true
          required: true

4. 定义发送邮件的服务类

定义邮件发送接口IMailService

package com.yyg.boot.mail;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/20
 * @Description 封装一个发邮件的接口,方便后边直接调用.
 */
public interface IMailService {

    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendSimpleMail(String to, String subject, String content);

    /**
     * 发送HTML邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    void sendHtmlMail(String to, String subject, String content);

    /**
     * 发送带附件的邮件
     *
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     */
    void sendAttachmentsMail(String to, String subject, String content, String filePath);

    /**
     * 发送模板邮件
     * @param to 收件人
     * @param subject 主题
     * @param fileName 邮件模板文件名称
     * @param model 邮件数据载体
     */
    void sendModelMail(String to, String subject, String fileName, Object model);

}

定义邮件发送实现类IMailServiceImpl

package com.yyg.boot.mail.impl;

import com.yyg.boot.mail.IMailService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/20
 * @Description Description
 */
@Slf4j
@Service
public class IMailServiceImpl implements IMailService {

    /**
     * Spring Boot 提供了一个发送邮件的简单抽象,使用的是下面这个接口,这里直接注入即可使用
     */
    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private Configuration configuration;

    /**
     * 配置文件中我的qq邮箱
     */
    @Value("${spring.mail.from}")
    private String from;

    /**
     * 简单文本邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //创建SimpleMailMessage对象
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发送人
        message.setFrom(from);
        //邮件接收人
        message.setTo(to);
        //邮件主题
        message.setSubject(subject);
        //邮件内容
        message.setText(content);
        //发送邮件
        mailSender.send(message);
    }

    /**
     * html邮件
     *
     * @param to      收件人
     * @param subject 主题
     * @param content 内容
     */
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        //获取MimeMessage对象
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(from);
            //邮件接收人
            messageHelper.setTo(to);
            //邮件主题
            message.setSubject(subject);
            //邮件内容,html格式
            messageHelper.setText(content, true);
            //发送
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送...");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        }
    }

    /**
     * 带附件的邮件
     * @param to       收件人
     * @param subject  主题
     * @param content  内容
     * @param filePath 附件
     */
    @Override
    public void sendAttachmentsMail(String to, String subject, String content, String filePath) {
        MimeMessage message = mailSender.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));
            ClassPathResource resource = new ClassPathResource(filePath);
            FileSystemResource file = new FileSystemResource(resource.getFile());
            helper.addAttachment(Objects.requireNonNull(file.getFilename()), file);
            //可以同时添加多个附件,只需要在这里直接添加第2,第3...附件就行了.
            //helper.addAttachment(fileName2, file2);
            mailSender.send(message);
            //日志信息
            log.info("邮件已经发送...");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("发送邮件时发生异常!", e);
        }
    }

    @Override
    public void sendModelMail(String to, String subject, String fileName, Object model) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);

            Template template = configuration.getTemplate(fileName);
            String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);

            helper.setText(html, true);

            mailSender.send(mimeMessage);

            //日志信息
            log.info("邮件已经发送...");
        } catch (MessagingException e) {
            log.error("发送邮件时发生异常!", e);
        } catch (TemplateException e) {
            e.printStackTrace();
            log.error("发送邮件时发生异常!", e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

5. 定义实体类

package com.yyg.boot.entity;

import lombok.Data;

import java.util.Date;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/20
 * @Description Description
 */
@Data
public class Employee {

    /**
     * 员工编号
     */
    private Long id;

    /**
     * 员工名称
     */
    private String username;

    /**
     * 合同期限
     */
    private Integer contractTerm;

    /**
     * 员工薪水
     */
    private Double salary;

    /**
     * 合同起始日期
     */
    private Date beginContract;

    /**
     * 合同截至日期
     */
    private Date endContract;

    /**
     * 部门名称
     */
    private String departmentName;

    /**
     * 职位名称
     */
    private String posName;

}

6. 创建入口类

package com.yyg.boot;

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

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/20
 * @Description Description
 */
@SpringBootApplication
public class MailApplication {

    public static void main(String[] args){
        SpringApplication.run(MailApplication.class,args);
    }

}

7. 创建Controller接口

7.1 定义发送简单邮件的接口方法:

@GetMapping("/simple")
public String sendSimpleMail() {
    iMailService.sendSimpleMail("收件箱@qq.com", "邮件标题", "邮件内容.....机密");
    return "success";
}

启动程序进行测试

邮件发送成功:
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第5张图片

去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第6张图片

7.2定义发送html格式邮件的接口方法:

@GetMapping("/html")
public String sendHtmlMail() {
    iMailService.sendHtmlMail("收件箱@qq.com", "邮件主题", "

邮件主题


邮件内容

"); return "success"; }

邮件发送成功:
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第7张图片

去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第8张图片

7.3创建发送带附件的邮件接口方法:

@GetMapping("/attachment")
public String sendAttachmentMail() {
    iMailService.sendAttachmentsMail("收件箱@qq.com", "主题:带附件的邮件", "有附件的邮件,不要错过哦...", "static/touxiang.png");
    return "success";
}

注意:

我这里是把附件直接放到了项目的resource/static目录下了,我们也可以存放到桌面等位置。

邮件发送成功:
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第9张图片

然后去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第10张图片

7.4创建发送模板邮件的接口方法:

首先利用FreeMarker创建页面模板。

${username}--你好,欢迎加入XXX大家庭!您的入职信息如下:

工号${id}
合同期限${contractTerm}年
员工薪资${salary}/月(美元)
合同起始日期${beginContract?string("yyyy-MM-dd")}
合同截至日期${endContract?string("yyyy-MM-dd")}
所属部门${departmentName}
职位${posName}

希望在未来的日子里,携手共进!

别忘了在application.yml文件中对freemarker进行配置:

spring:
  freemarker:
    template-loader-path: classpath:/templates/
   #spring.freemarker.prefix=
    suffix: .ftl
    cache: false
    charset: utf-8
    check-template-location: true
    content-type: text/html

创建接口方法

 @PostMapping("/model")
 public String sendModelMail(@RequestBody Employee employee) {
    iMailService.sendModelMail("收件箱@qq.com", "主题:新员工入职欢迎邮件--模板邮件", "mail.ftl", employee);
    return "success";
}

在postman中进行接口测试
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第11张图片

然后去目标邮箱的收件箱中进行查看,可以看到如下邮件内容,说明邮件发送成功!
SpringBoot2.x系列教程69--SpringBoot中整合Mail实现邮件发送_第12张图片

8. Controller完整代码

package com.yyg.boot.web;

import com.yyg.boot.entity.Employee;
import com.yyg.boot.mail.IMailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/4/20
 * @Description Description
 */
@RestController
@RequestMapping("/mail")
public class MailController {

    @Autowired
    private IMailService iMailService;

    @GetMapping("/simple")
    public String sendSimpleMail() {
        iMailService.sendSimpleMail("[email protected]", "邮件标题", "邮件内容.....机密");
        return "success";
    }

    @GetMapping("/html")
    public String sendHtmlMail() {
        iMailService.sendHtmlMail("[email protected]", "邮件主题", "

邮件主题


邮件内容

"); return "success"; } @GetMapping("/attachment") public String sendAttachmentMail() { iMailService.sendAttachmentsMail("[email protected]", "主题:带附件的邮件", "有附件的邮件,不要错过哦...", "static/touxiang.png"); return "success"; } @PostMapping("/model") public String sendModelMail(@RequestBody Employee employee) { iMailService.sendModelMail("[email protected]", "主题:新员工入职欢迎邮件--模板邮件", "mail.ftl", employee); return "success"; } }

9. 完整项目结构




 

你可能感兴趣的:(Spring,Boot,2,邮件发送)