SpringBoot系列——mail
前言
邮件是许多项目里都需要用到的功能,之前一直都是用JavaMail来发,现在Spring框架为使用JavaMailSender接口发送电子邮件提供了一个简单的抽象,Spring Boot为它提供了自动配置以及启动模块。springboot参考手册介绍:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-email
作为发送方,首先需要开启POP3/SMTP服务,登录邮箱后前往设置进行开启,开启后取得授权码。
POP3 :
POP3是Post Office Protocol 3的简称,即邮局协议的第3个版本,规定怎样将个人计算机连接到Internet的邮件服务器和下载电子邮件的电子协议。是因特网电子邮件的第一个离线协议标准,POP3允许用户从服务器上把邮件存储到本地主机(即自己的计算机)上,同时删除保存在邮件服务器上的邮件,而POP3服务器则是遵循POP3协议的接收邮件服务器,用来接收电子邮件的。
SMTP:
SMTP 的全称是“Simple Mail Transfer Protocol”,即简单邮件传输协议。是一组用于从源地址到目的地址传输邮件的规范,通过来控制邮件的中转方式。SMTP 协议属于 TCP/IP 协议簇,帮助每台计算机在发送或中转信件时找到下一个目的地。SMTP 服务器就是遵循 SMTP 协议的发送邮件服务器。
代码编写
maven引包,其中,邮件模板需要用到thymeleaf
<!-- 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>
<!-- springboot web(MVC)-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- springboot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
appliaction.propertise配置文件
#设置服务端口
server.port= # Email (MailProperties)
spring.mail.default-encoding=UTF-
spring.mail.host=smtp.qq.com
spring.mail.username=huanzi.qch@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
SpringBootMailServiceImpl.java
@Service
class SpringBootMailServiceImpl implements SpringBootMailService { @Autowired
private JavaMailSender mailSender; /**
* 发送方
*/
@Value("${spring.mail.username}")
private String from; /**
* 发送简单邮件
*
* @param to 接收方
* @param subject 邮件主题
* @param text 邮件内容
*/
@Override
public void sendSimpleMail(String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text); mailSender.send(message);
} /**
* 发送HTML格式的邮件
*
* @param to 接收方
* @param subject 邮件主题
* @param content HTML格式的邮件内容
* @throws MessagingException
*/
@Override
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
//true表示需要创建一个multipart message
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true); mailSender.send(message);
} /**
* 发送HTML格式的邮件,并可以添加附件
* @param to 接收方
* @param subject 邮件主题
* @param content HTML格式的邮件内容
* @param files 附件
* @throws MessagingException
*/
@Override
public void sendAttachmentsMail(String to, String subject, String content, List<File> files) throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
//添加附件
for(File file : files){
helper.addAttachment(file.getName(), new FileSystemResource(file));
} mailSender.send(message);
}
}
测试controller
@Autowired
private SpringBootMailService springBootMailService; @Autowired
private TemplateEngine templateEngine; @GetMapping("/index")
public String index() throws MessagingException {
//简单邮件
springBootMailService.sendSimpleMail("1726639183@qq.com","Simple Mail","第一封简单邮件"); //HTML格式邮件
Context context = new Context();
context.setVariable("username","我的小号");
springBootMailService.sendHtmlMail("1726639183@qq.com","HTML Mail",templateEngine.process("mail/mail",context)); //HTML格式邮件,带附件
Context context2 = new Context();
context2.setVariable("username","我的小号(带附件)");
ArrayList<File> files = new ArrayList<>();
files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试.txt"));
files.add(new File("C:\\Users\\Administrator\\Desktop\\上传测试2.txt"));
springBootMailService.sendAttachmentsMail("1726639183@qq.com","Attachments Mail",templateEngine.process("mail/attachment",context2),files); return "hello springboot!";
}
两个html模板,路径:myspringboot\src\main\resources\templates\mail\
mail.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Mail Templates</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p style="color: red;">这是一封HTML格式的邮件。</p>
</body>
</html>
attachment.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Mail Templates Accessory</title>
</head>
<body>
<h3><span th:text="${username}"></span>,你好!</h3>
<p>这是一封HTML格式的邮件。请收下附件!</p>
</body>
</html>
效果
Simple Mail

HTML Mail

Attachments Mail


后记
本文章部分参考:https://www.cnblogs.com/yangtianle/p/8811732.html
代码开源
代码已经开源、托管到我的GitHub、码云:
GitHub:https://github.com/huanzi-qch/springBoot
码云:https://gitee.com/huanzi-qch/springBoot
SpringBoot系列——mail的更多相关文章
- SpringBoot系列(十四)集成邮件发送服务及邮件发送的几种方式
往期推荐 SpringBoot系列(一)idea新建Springboot项目 SpringBoot系列(二)入门知识 springBoot系列(三)配置文件详解 SpringBoot系列(四)web静 ...
- springBoot系列教程07:异常捕获
发生异常是很正常的事,异常种类也是千奇百怪,发生异常并不可怕,只要正确的处理,并正确的返回错误信息并无大碍,如果不进行捕获或者处理,分分钟服务器宕机是很正常的事 所以处理异常时,最基本的要求就是发生异 ...
- SpringBoot系列——利用系统环境变量与配置文件的分支选择实现“智能部署”
前言 通过之前的博客:SpringBoot系列——jar包与war包的部署,我们已经知道了如果实现项目的简单部署,但项目部署的时候最烦的是什么?修改成发布环境对应的配置!数据库连接地址.Eureka注 ...
- Springboot 系列(十二)使用 Mybatis 集成 pagehelper 分页插件和 mapper 插件
前言 在 Springboot 系列文章第十一篇里(使用 Mybatis(自动生成插件) 访问数据库),实验了 Springboot 结合 Mybatis 以及 Mybatis-generator 生 ...
- Springboot 系列(九)使用 Spring JDBC 和 Druid 数据源监控
前言 作为一名 Java 开发者,相信对 JDBC(Java Data Base Connectivity)是不会陌生的,JDBC作为 Java 基础内容,它提供了一种基准,据此可以构建更高级的工具和 ...
- SpringBoot系列——Spring-Data-JPA(究极进化版) 自动生成单表基础增、删、改、查接口
前言 我们在之前的实现了springboot与data-jpa的增.删.改.查简单使用(请戳:SpringBoot系列——Spring-Data-JPA),并实现了升级版(请戳:SpringBoot系 ...
- SpringBoot系列——Spring-Data-JPA
前言 jpa是ORM映射框架,更多详情,请戳:apring-data-jpa官网:http://spring.io/projects/spring-data-jpa,以及一篇优秀的博客:https:/ ...
- SpringBoot系列——Spring-Data-JPA(升级版)
前言 在上篇博客中:SpringBoot系列——Spring-Data-JPA:https://www.cnblogs.com/huanzi-qch/p/9970545.html,我们实现了单表的基础 ...
- SpringBoot系列: SpringBoot Web项目中使用Shiro
注意点有:1. 不要启用 spring-boot-devtools, 如果启用 devtools 后, 不管是热启动还是手工重启, devtools总是试图重新恢复之前的session数据, 很有可能 ...
随机推荐
- [转载]ECMall模板解析语法与机制
ECMall模板解析语法与机制 2011-05-22 在ECMall模板中,用"{"开头,以"}"结尾就构成一个标签单元,"{"紧接着的单词 ...
- weka环境配置
java环境变量设置: 安装jdk到具体目录"ABC"下当前目录下应该有jdk+版本号和jre加版本号. 然后打开环境变量:新建JAVA_HOME内容是:jdk的安装目录.例如:D ...
- 解读IEEE 7417的软件体系架构描述的概念模型
本文将解读标准IEEE Std 1471-2000(密集型软件的体系结构描述推荐实施规程)的概念模型图部分,从中一窥作为软件架构师的进行架构设计的思考角度与策略.如果我们把世界当做一场游戏,现在要玩的 ...
- java实现wc.exe
Github地址:https://github.com/ztz1998/wc/tree/master 项目相关要求 实现一个统计程序,它能正确统计程序文件中的字符数.单词数.行数,以及还具备其他扩展功 ...
- 为什么我们要使用int类型来保存时间类型的数据。
1.如果数据保存的是timestamp类型那么,如果某个服务器系统时区配置错误,那么悲剧的是通过该服务器写入的时间都是有偏差的. 如果使用int类型保存unix时间戳的话,那么就是在前端展示的时候转 ...
- 'An instance 0x155e74a0 of class UIWebView was deallocated while key value observers were still registered with it.
在iOS和html混编的时候,当用iOS原生的navigation导航pop回去的时候,出现 *** Terminating app due to uncaught exception 'NSInte ...
- 剑指offer面试题25:二叉树中和为某一值的路径
题目:输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径.从根节点开始往下一直到叶节点所经过的节点形成一条路径. 解题思路:当使用前序遍历的方式访问某一节点时,把该节点添加到路径上 ...
- flask上下文(new)
flask源码解析之上下文 引入 对于flask而言,其请求过程与django有着截然不同的流程.在django中是将请求一步步封装最终传入视图函数的参数中,但是在flask中,视图函数中并没有请求参 ...
- 吴恩达机器学习笔记29-神经网络的代价函数(Cost Function of Neural Networks)
假设神经网络的训练样本有
- Numpy学习三:数组运算
1.转置 #reshape(shape)函数改变数组形状,shape是一个元组,表示数组的形状 创建一个包含15个元素的一维数组,通过reshape函数调整数组形状为3行5列的二维数组arr = np ...