当前位置: 代码迷 >> 综合 >> SpringBoot —— 实现邮件、短信的发送功能
  详细解决方案

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

热度:75   发布时间:2023-09-18 12:48:28

文章目录

  • 前言
  • 一、开启服务
    • 1.POP3和SMTP协议
    • 2.获取授权码
  • 二、使用步骤
    • 1.环境配置
    • 2.代码编写
    • 3.邮件发送测试
    • 4.短信发送

前言

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邮箱为例:
SpringBoot —— 实现邮件、短信的发送功能
开启服务之后,会获得一个授权码:成功开启POP3/SMTP服务,在第三方客户端登录时,密码框请输入以下授权码:

二、使用步骤

1.环境配置

引入依赖

<!-- springboot 邮件mail -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--Thymeleaf-->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

application.yml

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

2.代码编写

SendMail.java

@Service
public class SendMail {
    private final static Logger LOGGER = LoggerFactory.getLogger(SendMail.class);@Autowiredprivate 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<File> files) {
    MimeMessage message = mailSender.createMimeMessage();// true表示需要创建一个multipart messagetry {
    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 {
    @Autowiredprivate SendMail sendMail;@Autowiredprivate 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<File> files = new ArrayList<>();sendMail.sendHtmlMail(sendTo, subject, templateEngine.process(template, context), files);return ApiResponse.ok();}}

mail.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>Title</title>
</head>
<body>
<p>hello 欢迎加入 荣华富贵 大家庭,您的入职信息如下:</p>
<table border="1"><tr><td>姓名</td><td th:text="${username}"></td></tr><tr><td>工号</td><td th:text="${num}"></td></tr>
</table>
<div style="color: #ff1a0e">加油加油</div>
<div style="color: #ff1a0e">努力努力!</div>
<div style="color: #ff1a0e">今天睡地板,明天当老板!</div>
</body>
</html>

3.邮件发送测试

启动项目,打开http://localhost:8080/doc.html
SpringBoot —— 实现邮件、短信的发送功能
调试接口,效果如下:
SpringBoot —— 实现邮件、短信的发送功能
SpringBoot —— 实现邮件、短信的发送功能

4.短信发送

短信发送通过调用API实现,具体参考:https://blog.csdn.net/qq_34383510/article/details/115939788

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

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