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...

相关推荐
JavaGuide1 小时前
一个 SKILL.md 拿下 2.3 万 Star:让 Codex/Claude Code 少说废话、先给答案
前端·后端
陈随易8 小时前
pm2 替代品,nodejs&bun 线上部署必备工具
前端·后端·程序员
丘山一郎9 小时前
Spring 中的IOC控制反转 和DI依赖注入
java·后端·spring
码视野9 小时前
基于 Spring Boot + Vue3 的【大学英语四六级 (CET-4/6) 作文智能评分与句式润色系统】设计与实现(含PRD/三端高保真源码/大屏)
java·前端·人工智能·spring boot·后端·vue3
MetaLite9 小时前
Spring-AOP自调用为什么失效-AopContext真能解决吗
java·后端·spring
MC皮蛋侠客10 小时前
Tauri 2.x 系列(五):调用系统 API——官方插件、Rust crate 与原生能力
开发语言·后端·rust
Profile排查笔记11 小时前
指纹浏览器怎么设置 IP?代理配置、检测与排错流程
前端·人工智能·后端·自动化
IT_陈寒13 小时前
SpringBoot自动配置失效?你可能漏了这个小开关
前端·人工智能·后端
摇滚侠13 小时前
《SpringBoot 3:入门与应用实战》第 9 章 使用 WebMvc 开发应用 阅读笔记 1
spring boot·笔记·后端
用户83562907805113 小时前
使用 Python 在 Excel 中插入 OLE 对象
后端·python