SpringBoot —— 实现邮件、短信的发送功能

前言

SpringBoot系列Demo代码,实现邮件和短信的发送。

一、开启服务

1.POP3和SMTP协议

Spring框架为使用JavaMailSender接口发送电子邮件提供了一个简单的抽象,Spring Boot为它提供了自动配置以及启动模块。

在使用Spring Boot发送邮件之前,要开启POP3和SMTP协议,需要获得邮件服务器的授权码

SMTP 协议全称为 Simple Mail Transfer Protocol,译作简单邮件传输协议,它定义了邮件客户端软件与 SMTP 服务器之间,以及 SMTP 服务器与 SMTP 服务器之间的通信规则。

POP3 协议全称为 Post Office Protocol ,译作邮局协议,它定义了邮件客户端与 POP3 服务器之间的通信规则

2.获取授权码

以QQ邮箱为例:

在这里插入图片描述

开启服务之后,会获得一个授权码:成功开启POP3/SMTP服务,在第三方客户端登录时,密码框请输入以下授权码:

二、使用步骤

1.环境配置

引入依赖



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



    org.springframework.boot
    spring-boot-starter-thymeleaf

application.yml

spring:
  # 数据源
  datasource:
    url: jdbc:mysql://localhost:3306/local_develop?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver
  profiles:
    active: @spring.profiles.active@
  # 邮件
  mail:
    default-encoding: utf-8
    # 配置 SMTP 服务器地址
    host: smtp.qq.com
    #发送方邮件名
    username: 
    #授权码
    password: 
    # thymeleaf模板格式
    thymeleaf:
      cache: false
      encoding: UTF-8
      mode: HTML
      servlet:
        content-type: text/html
      prefix: classpath:/templates/
      suffix: .html

2.代码编写

SendMail.java

@Service
public class SendMail {

    private final static Logger LOGGER = LoggerFactory.getLogger(SendMail.class);

    @Autowired
    private JavaMailSender mailSender;

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

    /**
     * 发送简单邮件
     *
     * @param sendTo  接收人
     * @param subject 邮件主题
     * @param text    邮件内容
     */
    public void sendSimpleMail(String sendTo, String subject, String text) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(sendFrom);
        message.setTo(sendTo);
        message.setSubject(subject);
        message.setText(text);

        mailSender.send(message);
    }

    /**
     * 发送HTML格式的邮件,并可以添加附件
     *
     * @param sendTo  接收人
     * @param subject 邮件主题
     * @param content 邮件内容(html)
     * @param files   附件
     * @throws MessagingException
     */
    public void sendHtmlMail(String sendTo, String subject, String content, List files) {
        MimeMessage message = mailSender.createMimeMessage();
        // true表示需要创建一个multipart message
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sendFrom);
            helper.setTo(sendTo);
            helper.setSubject(subject);
            helper.setText(content, true);

            //添加附件
            for (File file : files) {
                helper.addAttachment(file.getName(), new FileSystemResource(file));
            }
            mailSender.send(message);
        } catch (MessagingException e) {
            LOGGER.warn("邮件发送出错:{}", e);
        }
    }
}

SendMailController.java

@Api(value = "邮件发送接口", tags = "邮件发送接口")
@RestController
@RequestMapping("/index")
public class SendMailController {

    @Autowired
    private SendMail sendMail;

    @Autowired
    private TemplateEngine templateEngine;

    @ApiOperation(value = "发送简单邮件", notes = "发送简单邮件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),
            @ApiImplicitParam(name = "subject", required = false, value = "邮件主题"),
            @ApiImplicitParam(name = "text", required = false, value = "邮件内容"),
    })
    @GetMapping("/sendSimpleMail")
    public ApiResponse sendSimpleMail(@RequestParam String sendTo,
                                      @RequestParam(required = false) String subject,
                                      @RequestParam(required = false) String text) {
        sendMail.sendSimpleMail(sendTo, subject, text);
        return ApiResponse.ok();
    }

    @ApiOperation(value = "发送HTML格式的邮件", notes = "使用Thymeleaf模板发送邮件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),
            @ApiImplicitParam(name = "subject", required = false, value = "邮件主题"),
            @ApiImplicitParam(name = "content", required = true, value = "邮件模板"),
    })
    @GetMapping("/sendHtmlMail")
    public ApiResponse sendHtmlMail(@RequestParam String sendTo,
                                    @RequestParam(required = false) String subject,
                                    @RequestParam String content) {
        Context context = new Context();
        context.setVariable("username", "xx");
        context.setVariable("num", "007");
        // 模板
        String template = "mail/" + content;
        List files = new ArrayList<>();
        sendMail.sendHtmlMail(sendTo, subject, templateEngine.process(template, context), files);
        return ApiResponse.ok();
    }

}

mail.html




    
    Title


hello 欢迎加入 荣华富贵 大家庭,您的入职信息如下:

姓名
工号
加油加油
努力努力!
今天睡地板,明天当老板!

3.邮件发送测试

启动项目,打开http://localhost:8080/doc.html

在这里插入图片描述

调试接口,效果如下:
在这里插入图片描述

在这里插入图片描述

4.短信发送

短信发送通过调用API实现,具体参考:https://www.jianshu.com/p/89b4244d516c

本文参考:http://springboot.javaboy.org/2019/0717/springboot-mail

« 上一章:SpringBoot —— 整合Logback,输出日志到文件
» 下一章:SpringBoot —— 多线程定时任务的实现(注解配置、task:annotation-driven配置)

创作不易,关注、点赞就是对作者最大的鼓励,欢迎在下方评论留言
求关注,定期分享Java知识,一起学习,共同成长。

你可能感兴趣的:(SpringBoot —— 实现邮件、短信的发送功能)