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

相关推荐
fishfinal13 分钟前
VitePress 架构重构实录:拒绝扁平与耦合,重构你的独立文档项目
后端
Java内核笔记21 分钟前
方法级 trace 看不出第几轮:给 Agent 补一层轮次维度
人工智能·spring boot·后端
数据库小学妹25 分钟前
数据库容量规划:四个数与扩容触发线
运维·数据库·后端
AAA修煤气灶刘哥26 分钟前
DSH Super-agent 双层架构:如何兼顾后台执行与持续响应
人工智能·后端·设计模式
泡海椒30 分钟前
jquick-pdf 资源使用率报表模板:政务云集群水位的图表版与表格版怎么选
后端
用户50800705462831 分钟前
1元机器到手后,我拿它跑了一套微服务测试环境
后端
郭生37 分钟前
dedecms等php类cms静态生成速度慢或超时原因及解决方法
后端
Gopher_HBo38 分钟前
Go pprof:五个字段,凭什么管住六种剖析?
后端
生锈的键盘39 分钟前
Docker 环境下 uv 与 Playwright 最佳实践:从镜像构建到多服务版本对齐
后端
学以智用1 小时前
CKEditor5 完整详解
前端·后端