当前位置: 首页 > news >正文

SpringBoot 2.x ——使用 mail 实现邮件发送

文章目录

  • 前言
  • 环境、版本等
  • pom依赖引入
  • springboot项目配置文件
    • 获取邮箱授权码
    • 配置properties文件
  • 定义接口信息接收类
  • 编写邮件发送服务类
  • 编写接口
  • swagger测试
    • 1、简单邮件发送
    • 2、html格式发送(支持附件)

前言

最近再看xxl-job的源码,其中在邮件告警通知中使用到了告警信息邮件通知的方式,挺有意思的,特写一篇文章进行简单的配置和使用。

环境、版本等

  • springboot 2.1.4.RELEASE
  • jdk 1.8

pom依赖引入

springboot的版本就已经对mail组件进行了控制,只需要引入对应的依赖即可,无需单独设置版本。(也可以设定指定的版本号)

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-mail</artifactId>
</dependency>

springboot项目配置文件

由于加入了spring-boot-starter-mail依赖组件,此时如果需要使用mail功能,还需要进行下面的几项配置。

获取邮箱授权码

进入QQ邮箱的设置,找到账户
在这里插入图片描述
账户项中下滑至POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务
在这里插入图片描述

选择生成授权码。需要发送确认短信信息,当发送成功后,将会获得当前邮箱的授权码信息
将授权码信息复制粘贴到spring.mail.password中即可!

配置properties文件

创建application.properties文件,并在其中配置如下信息:

server.port=80spring.mail.host=smtp.qq.com
spring.mail.port=25
spring.mail.username=302592372@qq.com
spring.mail.from=302592372@qq.com    # 邮件发送者
spring.mail.password=邮箱授权码
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory

定义接口信息接收类

主要是接口传递参数使用,如下结构:

import lombok.Data;
import java.io.Serializable;@Data
public class MailRequest implements Serializable {/*** 接收人*/private String sendTo;/*** 邮件主题*/private String subject;/*** 邮件内容*/private String text;/*** 附件路径*/private String filePath;}

编写邮件发送服务类

编写邮件发送操作的服务类,使用两种方式:简单邮件内容发送html邮件内容发送

import cn.xj.emails.uo.MailRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Date;@Slf4j
@Service
public class SendMailService {@Autowiredprivate JavaMailSender javaMailSender;@Value("${spring.mail.from}")private String sendMailer;/*** 简单邮件内容发送* @param mailRequest*/public void sendSimpleMail(MailRequest mailRequest) {SimpleMailMessage message = new SimpleMailMessage();//邮件发件人message.setFrom(sendMailer);//邮件收件人 1或多个message.setTo(mailRequest.getSendTo().split(","));//邮件主题message.setSubject(mailRequest.getSubject());//邮件内容message.setText(mailRequest.getText());//邮件发送时间message.setSentDate(new Date());javaMailSender.send(message);log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());}/*** Html格式邮件,可带附件* @param mailRequest*/public void sendHtmlMail(MailRequest mailRequest) {MimeMessage message = javaMailSender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message,true);//邮件发件人helper.setFrom(sendMailer);//邮件收件人 1或多个helper.setTo(mailRequest.getSendTo().split(","));//邮件主题helper.setSubject(mailRequest.getSubject());//邮件内容helper.setText(mailRequest.getText(),true);//邮件发送时间helper.setSentDate(new Date());String filePath = mailRequest.getFilePath();if (StringUtils.hasText(filePath)) {FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = filePath.substring(filePath.lastIndexOf(File.separator));helper.addAttachment(fileName,file);}javaMailSender.send(message);log.info("发送邮件成功:{}->{}",sendMailer,mailRequest.getSendTo());} catch (MessagingException e) {log.error("发送邮件时发生异常!",e);}}
}

编写接口

制定一个测试 controller,进行简单的接口开发。

import cn.xj.emails.service.SendMailService;
import cn.xj.emails.uo.MailRequest;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
@RequestMapping("/email")
@Api(value = "发送邮件接口",tags = {"发送邮件接口"})
public class TestController {@Autowiredprivate SendMailService sendMailService;@PostMapping("/simple")public void SendSimpleMessage(@RequestBody MailRequest mailRequest) {sendMailService.sendSimpleMail(mailRequest);}@PostMapping("/html")public void SendHtmlMessage(@RequestBody MailRequest mailRequest) { sendMailService.sendHtmlMail(mailRequest);}
}

swagger测试

为了测试的方便,项目中整合了swagger2进行接口测试,当然也可以使用postman等工具。

1、简单邮件发送

/email/simple

在这里插入图片描述
收到邮件如下:
在这里插入图片描述

2、html格式发送(支持附件)

/email/html

在这里插入图片描述
收到的邮件如下所示:
在这里插入图片描述

http://www.lryc.cn/news/22514.html

相关文章:

  • 项目结束先别着急庆祝,项目经理还有这些事要做
  • 没想到的 IIFE
  • 「牛客网C」初学者入门训练BC156
  • 【Proteus仿真】【STM32单片机】粮仓温湿度控制系统设计
  • 九年时间,倾情投入,JumpServer开源堡垒机v3.0正式发布
  • 【ROS学习笔记5】服务通信
  • “华为杯”研究生数学建模竞赛2006年-【华为杯】A题:Ad Hoc 网络中的区域划分和资源分配问题(附获奖论文)
  • 编写第一个JAVA程序,常见踩坑记录
  • 求职陷阱:Lazarus组织以日本瑞穗銀行等招聘信息为诱饵的攻击活动分析
  • 【C语言每日一题】判断字符串旋转结果(附加字符串左旋详解)
  • SpringSecurity+JWT+Redis进行用户鉴权和接口权限的控制
  • 七大排序(Java)
  • 分享一些可以快速掌握python语法的小技巧
  • 1.FFmpeg-音视频基础
  • Parasoft的自动化测试平台到底强在哪?
  • FastDDS-0.简介
  • Flutter入门进阶之旅 -开源Flutter项目
  • Opencv项目实战:21 美国ASL手势识别
  • 强化学习RL 01: Reinforcement Learning 基础
  • C语言之练习题合集
  • sublimeText3新建文件自动添加注释头
  • AndroidStudio打包HBuilderX的H5+项目为安卓App【一次过,无任何异常报错】
  • 【Linux】进程概念
  • 使用pyinstaller库打包exe时显示KeyError怎么办
  • k8s新增节点机器,无法拉取和推送镜像的解决方案
  • 测试报告踩坑的点
  • 【Java】创建多线程的四种方式
  • 【数据结构】队列的接口实现(附图解和源码)
  • 日本知名动画公司东映动画加入 The Sandbox 元宇宙
  • QuickHMI Hawk R3 Crack