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

文章目录 前言 一、开启服务

复制代码
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邮箱为例:

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

二、使用步骤 1.环境配置 引入依赖

xml 复制代码
<!-- 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

yaml 复制代码
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 {

typescript 复制代码
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<File> 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 {

less 复制代码
@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<File> 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实现,具体参考:blog.csdn.net/qq_34383510...

本文参考:springboot.javaboy.org/2019/0717/s...

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

原文链接:blog.csdn.net/qq_34383510...

相关推荐
大阳光男孩3 小时前
Spring Boot 整合 Debezium 实现 MySQL 增量数据监听(嵌入式版)
spring boot·后端·mysql
皮皮林5513 小时前
ThreadLocal 不香了?ScopedValue才是王道?
后端
X-⃢_⃢-X4 小时前
一、第一阶段:认识 Spring Boot
java·spring boot·后端
前端工作日常4 小时前
我学习到的Java程序的生命周期
java·后端
AskHarries6 小时前
GitHub 登录配置流程
后端
Sinclair8 小时前
安企CMS的安装-常见安装问题排查
运维·后端
Sinclair8 小时前
安企CMS的安装-安装引导与初始化
运维·后端
Sinclair8 小时前
安企CMS的安装-源码编译安装
运维·后端·go
Sinclair8 小时前
安企CMS的安装-同一服务器多站点部署
运维·后端
Sinclair8 小时前
安企CMS的安装-服务器手动部署
运维·后端