技术标签: Spring Boot
相信使用过Spring的众多开发者都知道Spring提供了非常好用的JavaMailSender接口实现邮件发送,在Spring Boot的Starter模块中也为此提供了自动化配置,下面通过实例看看如何在Spring Boot中使用JavaMailSender发送邮件,本文以@163.com邮箱为例阐述。
邮件服务在互联网早期就已经出现,如今已成为人们互联网生活中必不可少的一项服务。那么邮件服务是怎么工作的呢?如下给出邮件发送与接收的典型过程:
1、发件人使用SMTP协议传输邮件到邮件服务器A;
2、邮件服务器A根据邮件中指定的接收者,投送邮件至相应的邮件服务器B;
3、收件人使用POP3协议从邮件服务器B接收邮件。
SMTP(Simple Mail Transfer Protocol)是电子邮件(email)传输的互联网标准,定义在RFC5321,默认使用端口25;
POP3(Post Office Protocol - Version 3)主要用于支持使用客户端远程管理在服务器上的电子邮件。定义在RFC 1939,为POP协议的第三版(最新版)。
这两个协议均属于TCP/IP协议族的应用层协议,运行在TCP层之上。
我们日常收发邮件使用的客户端、Web Mail的背后都在运行着这两个协议,完成收发邮件的过程。而现在我们需要使用SMTP协议来把发送给用户的邮件传输到邮件服务器。
从客户端传输邮件到服务器需要双方的配合,而规则就定义在SMTP协议中。我们现在需要做的是找一个SMTP服务器,再实现一个SMTP客户端,然后让客户端发送邮件到服务器。
电子邮件具有全世界通用的协议。所以你可以使用任何一种邮件的客户端,以任何一种方式去查看你的邮件。这个世界上的电子邮件客户端不下千种,他们都以不同的方式去满足了不同需求的人群,邮件有以下特点:
① 企业内部的沟通,邮件服务还是被认为“正式”的,比即时通信“可靠”。
② 支持转发/抄送,公开的,统一的通信协议,能够存档。
开启SMTP服务器,设置授权码,后续编写代码需要改授权码,编码中的密码非邮箱登录密码而是授权码,如:设置授权码为:123456。
① Gradle添加Spring Mail依赖
compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail'
② 修改application.properties,添加邮箱配置
##################################---Spring Mail发送邮件---##############################################
# JavaMailSender 邮件发送的配置
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.163.com
spring.mail.port=465
[email protected]
# 邮箱开启的授权码
spring.mail.password=123456
spring.mail.properties.smtp.auth=true
spring.mail.properties.smtp.starttls.enable=true
spring.mail.properties.smtp.starttls.required=true
spring.mail.properties.mail.smtp.ssl.enable=true
package com.javalsj.blog.mail;
import java.io.File;
import java.util.Map;
import javax.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import com.javalsj.blog.common.FileUtil;
/**
* @description 发送邮件工具,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
* @author WANGJIHONG
* @date 2018年3月14日 下午10:17:40
* @Copyright 版权所有 (c) www.javalsj.com
* @memo 无备注说明
*/
@Component
public class JavaMailUtil {
private final Logger logger = LoggerFactory.getLogger(getClass());
/**
* Java邮件发送器
*/
@Autowired
private JavaMailSender mailSender;
/**
* thymeleaf模板引擎
*/
@Autowired
private TemplateEngine templateEngine;
/**
* 发送不含附件,且不含嵌入html静态资源页面的纯文本简单邮件
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receiver
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopy
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param text
* 邮件内容 如:测试邮件逗你玩的。
*/
public void sendSimpleEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
throws Exception {
sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, null);
}
/**
* 发送含嵌入html静态资源页面, 但不含附件的邮件
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receivers
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopys
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param text
* 邮件内容 如: <html><body>
* <h1>213123</h1></body></html>
*/
public void sendHtmlEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text)
throws Exception {
sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
}
/**
* 发送含附件,但不含嵌入html静态资源页面的邮件
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receivers
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopys
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param text
* 邮件内容 如:测试邮件逗你玩的。
* @param attachmentFilePaths
* 附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
* http://www.javalsj.com/resource/test2.jpg
*/
public void sendAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
String text, String[] attachmentFilePaths) throws Exception {
sendMimeMail(deliver, receivers, carbonCopys, subject, text, false, attachmentFilePaths);
}
/**
* 发送含附件,且含嵌入html静态资源页面的邮件
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receivers
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopys
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param text
* <html><body><img src=\"cid:test\"><img
* src=\"cid:test2\"></body></html>
* @param attachmentFilePaths
* 附件文件路径 如:http://www.javalsj.com/resource/test.jpg,
* http://www.javalsj.com/resource/test2.jpg
* 需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
*/
public void sendHtmlAndAttachmentsEmail(String deliver, String[] receivers, String[] carbonCopys, String subject,
String text, String[] attachmentFilePaths) throws Exception {
sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, attachmentFilePaths);
}
/**
* 发送thymeleaf模板邮件
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receivers
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopys
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param thymeleafTemplatePath
* 邮件模板 如:mail\mailTemplate.html。
* @param thymeleafTemplateVariable
* 邮件模板变量集
*/
public void sendTemplateEmail(String deliver, String[] receivers, String[] carbonCopys, String subject, String thymeleafTemplatePath,
Map<String, Object> thymeleafTemplateVariable) throws Exception {
String text = null;
if (thymeleafTemplateVariable != null && thymeleafTemplateVariable.size() > 0) {
Context context = new Context();
thymeleafTemplateVariable.forEach((key, value)->context.setVariable(key, value));
text = templateEngine.process(thymeleafTemplatePath, context);
}
sendMimeMail(deliver, receivers, carbonCopys, subject, text, true, null);
}
/**
* 发送的邮件(支持带附件/html类型的邮件)
*
* @param deliver
* 发送人邮箱名 如: [email protected]
* @param receivers
* 收件人,可多个收件人 如:[email protected],[email protected]
* @param carbonCopys
* 抄送人,可多个抄送人 如:[email protected]
* @param subject
* 邮件主题 如:您收到一封高大上的邮件,请查收。
* @param text
* 邮件内容 如:测试邮件逗你玩的。 <html><body><img
* src=\"cid:attchmentFileName\"></body></html>
* @param attachmentFilePaths
* 附件文件路径 如:
* 需要注意的是addInline函数中资源名称attchmentFileName需要与正文中cid:attchmentFileName对应起来
* @throws Exception
* 邮件发送过程中的异常信息
*/
private void sendMimeMail(String deliver, String[] receivers, String[] carbonCopys, String subject, String text,
boolean isHtml, String[] attachmentFilePaths) throws Exception {
StopWatch stopWatch = new StopWatch();
try {
stopWatch.start();
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
helper.setFrom(deliver);
helper.setTo(receivers);
helper.setCc(carbonCopys);
helper.setSubject(subject);
helper.setText(text, isHtml);
// 添加邮件附件
if (attachmentFilePaths != null && attachmentFilePaths.length > 0) {
for (String attachmentFilePath : attachmentFilePaths) {
File file = new File(attachmentFilePath);
if (file.exists()) {
String attachmentFile = attachmentFilePath
.substring(attachmentFilePath.lastIndexOf(File.separator));
long size = FileUtil.getDirSize(file);
if (size > 1024 * 1024) {
String msg = String.format("邮件单个附件大小不允许超过1MB,[%s]文件大小[%s]。", attachmentFilePath,
FileUtil.formatSize(size));
throw new RuntimeException(msg);
} else {
FileSystemResource fileSystemResource = new FileSystemResource(file);
helper.addInline(attachmentFile, fileSystemResource);
}
}
}
}
mailSender.send(mimeMessage);
stopWatch.stop();
logger.info("邮件发送成功, 花费时间{}秒", stopWatch.getTotalTimeSeconds());
} catch (Exception e) {
logger.error("邮件发送失败, 失败原因 :{} 。", e.getMessage(), e);
throw e;
}
}
}
@RequestMapping(value = "/sendSimpleEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public Result sendSimpleEmail() {
Result result;
try {
javaMailUtil.sendSimpleEmail("[email protected]", new String[] { "[email protected]", "[email protected]" },
new String[] { "[email protected]" }, "您收到一封高大上的邮件,请查收。", "测试邮件逗你玩的。");
result = ResultFactory.buildSuccessResult(null);
} catch (Exception e) {
result = ResultFactory.buildFailResult(e.getMessage());
}
return result;
}
效果如下:
mailTemplate.html页面代码:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>邮件模板</title>
</head>
<body>
<div>
用户名:<input th:text="${username}"/> <br />
密码: <input th:text="${password}"/>
</div>
</body>
</html>
控制器测试代码:
@RequestMapping(value = "/sendTemplateEmail", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
@ResponseBody
public Result sendTemplateEmail() {
Result result = null;
try {
String thymeleafTemplatePath = "mail/mailTemplate";
Map<String, Object> thymeleafTemplateVariable = new HashMap<String, Object>();
thymeleafTemplateVariable.put("username", "javalsj");
thymeleafTemplateVariable.put("password", "123456");
javaMailUtil.sendTemplateEmail("[email protected]",
new String[] { "[email protected]", "[email protected]" },
new String[] { "[email protected]" },
"您收到一封高大上的邮件,请查收。",
thymeleafTemplatePath,
thymeleafTemplateVariable);
result = ResultFactory.buildSuccessResult(null);
} catch (Exception e) {
result = ResultFactory.buildFailResult(e.getMessage());
}
return result;
}
效果如下:
本文使用Spring Boot + JavaMailSender + Thymeleaf实现了服务端发送纯文本邮件、html邮件、附件邮件以及Thymeleaf模板邮件功能,由于Spring Boot默认模板引擎为Thymeleaf,所以使用默认的Thymeleaf自动配置即可,本文未做Thymeleaf的单独配置。
文章浏览阅读319次。求集合中满足一个值的子集和测试数据:43113 24 11 7结果:{13,11,7}{24,7}#include<iostream>using namespace std;int *x,*y;int size,sum;void output(){ int count = 0;//计算子集中的个数,这个只是用来控制是否输出逗号的情况 int tempsum = 0; for(int i = 1;i <= size;i++){ if(y[i] !_旅行商问题测试数据
文章浏览阅读846次。请编写一个函数int prime(int n)函数,该函数实现判断n是否为素数,然后调用该函数。如果n是素数,则输出Yes,否则输出No。_程序调用prime函数,判断输入的一个整数是否为素数,是则打印yes,否则打印no
文章浏览阅读4.3w次,点赞74次,收藏299次。Robot类用于为测试自动化、自运行演示程序和其他需要控制鼠标和键盘的应用程序生成本机系统输入事件。Robot 的主要目的是便于 Java 平台实现自动测试。_robot类
文章浏览阅读2.9w次,点赞31次,收藏134次。[ app.json 文件内容错误] app.json: 在项目根目录未找到 app.json_[ app.json 文件内容错误] app.json: 在项目根目录未找到 app.json (env: windows
文章浏览阅读28次。Python3.7.7+Django+Mysql5.7+pip list+HBuilderX(Vscode也行)+Vue+Pychram社区版。2. 前端:vue+css+javascript+jQuery+easyUI+highcharts。2.IDE环境:Python和Python 社区版都可以。Django + Vue +Python+Mysql 等等组成,B/S模式等等。该项目含有源码、文档、程序、数据库、配套开发软件、软件安装教程。1. 后端:Python、Vue、Django、Mysql。
文章浏览阅读109次。作者:废物大师兄来源:https://www.cnblogs.com/cjsblog/p/9712457.html1、引言读写分离要做的事情就是对于一条SQL该选择哪个数据库去执行,至于谁..._springboot实现读写分离mysql
文章浏览阅读499次,点赞8次,收藏6次。计数排序的时间复杂度为O(n+k),其中n是需要排序的元素数量,k是数组中的最大值与最小值的差值。这是因为计数排序需要遍历整个数组来统计元素出现的次数,然后还需要执行一次线性复制操作来将排序后的元素复制回原始数组。
文章浏览阅读920次,点赞24次,收藏21次。通过实现驾驶员、驾驶证、行驶证、通知公告、检测员、检测预约、检测接单、检测结果等系统功能,该软件系统将全面改善车辆检测的流程和效果。在当前的车辆检测市场中,大多数检测站都采用传统的纸质文档管理和人工检测方式,这不仅增加了检测成本,还可能因为人为错误或疏忽导致安全隐患。因此,开发一款基于网页的车辆检测站登录软件,有助于实现信息化管理和自动化检测,从而降低事故风险,提高道路安全。通过实现以上功能,本研究旨在提高车辆检测的效率和质量,降低道路事故风险,为社会的安全稳定做出贡献。第五阶段:撰写论文(3周)_网页设计在机动车检测中的应用
文章浏览阅读1.3k次。文章目录问题描述解决方案问题描述有这么一个html页面,具体代码如下:Nginx_CORS.html<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-wid..._nginx使用了代理转发就不会有跨域问题吗
文章浏览阅读3.6k次,点赞5次,收藏37次。java遍历集合的四种方式:普通for循环迭代器加强for循环(foreach)list.forEach_java集合遍历
文章浏览阅读291次。本文将在win10的环境下安装jdk16、配置环境变量。1.下载JDK(1)打开官网下载最新的JDK(Java SE Development Kit, JDK)(2)选择对应的版本(3)双击下载的exe进行安装在安装过程中可以改变安装位置也可以不改变,但是安装的位置一定要记住!!!!这关系到后面设置环境变量。然后安装过程中其它的选项就next~(4)配置环境变量一共需要配置3个系统环境变量。此电脑–属性–高级系统设置–环境变量—新建系统变量一定注意是系统变量!!!!别搞错了!!!!_java16.02安装
文章浏览阅读720次。1 赛题C 题 电商物流网络包裹应急调运与结构优化问题电商物流网络由物流场地(接货仓、分拣中心、营业部等)和物流场地之间的运输线路组成,如图 1 所示。受节假日和“双十一”、“618”等促销活动的影响,电商用户的下单量会发生显著波动,而疫情、地震等突发事件导致物流场地临时或永久停用时,其处理的包裹将会紧急分流到其他物流场地,这些因素均会影响到各条线路运输的包裹数量,以及各个物流场地处理的包裹数量。_数学建模物流配网络问题