技术标签: 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的单独配置。
文章浏览阅读1.1w次。七牛是专注文件存储的第三方服务商,服务较好。自己最近做到服务器存储图片的时候就想到用七牛来做,将图片或者文件存放在七牛,然后自己服务器只存放资源存放在七牛文件的url。今天主要分享两个内容:凭证的获取,安卓上传文件在做之前还是先把官方文档好好读几遍比较好首先说说凭证,七牛对所有上传的资源都需要身份验证,就是通过凭证来验证,验证通过,那么就可以成功上传文件,不通过,七牛服务器会反_7牛 s3存储的使用
文章浏览阅读3w次,点赞32次,收藏114次。Windows10 -64 安装tensorflow遇到的:cuda安装后找不到安装文件目录目录 一、错误:cuda安装后找不到安装文件目录二、查看cuda驱动程序的版本三、补充内容四、执行测试程序出错五、常用命令总结 一、错误:cuda安装后找不到安装文件目录原因是:将临时解压目录和安装目录设置成一样的了,导致安装结束,临时解压目录被删除,所以安装目录也被删除了;..._没有nvidia gpu computing toolkit文件夹
文章浏览阅读1.1k次。本文主要对memcache内部Big-O、LRU算法、内存分配(Memory allocation)、一致性哈希(Consistent hashing)等进行了深入剖析,并举例生动形象描述了一致性哈希算法_memcache 架构分析
文章浏览阅读2.1k次。人事部统计员小马负责本次公务员考试成绩数据的整理,按照下列要求帮助小马完成相关的整理、统计和分析工作:1.将考生文件夹下的工作簿文档“Excel素材.xlsx”另存为“Excel.xlsx”(“.xlsx”为文件扩展名),之后所有的操作均基于此文件,否则不得分。操作过程中,不可以随意改变工作表中数据的顺序。2.将考生文件夹下的工作簿“行政区划代码对照表.xlsx”中的工作表“Sheet1”复制到工..._excel准考证号的第四位为1,考试类别为a考试成绩
文章浏览阅读135次。跟你说,昨天......马云远赴非洲为他们颁奖......他们是谁呢?南非当地时间8月7日,来自非洲各国的一线野生动物巡护员齐聚开普敦。马云代表阿里巴巴公益基金会和桃花源生态保护基金会为他们颁奖。这群用生命保护大象、狮子和犀牛的巡护员们,第一次得到来自中国的资金和技术支持。在颁奖现场,每一位嘉宾的座位上都摆着一只可爱的非洲野生动物公仔。它们..._史上最危险的工作但是奖金最多
文章浏览阅读4k次。这里讨论两种多线程访问UI控件的方法,线程完成后更新Lable控件如下图,第一种方式为方式1按钮按下,线程运行,并更新label第二种方法为按下方式2按钮,线程运行,完成后更新label 新建winform项目程序,布局如上,大家可以不用配色,简单即可引用using System.Threading; 第一种方法:使用delegate和invoke来从其他线程中调用控件 当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它,所以我们判断这个属性来更新label的值 _winform多线程访问控件
文章浏览阅读2.9w次,点赞16次,收藏27次。我采用的.ini文件[uwsgi]master = truewsgi-file=myppt/wsgi.pyprocesses = 1threads = 2chdir = /www/wwwroot/ppt_jpg/myppt/http = 127.0.0.1:9876virtualenv=/www/wwwroot/ppt_jpg/myppt/ppt_venvdaemonize=uw..._uwsgi harakiri
文章浏览阅读7.4k次,点赞14次,收藏47次。前言: 最近准备在windows上面用ffmpeg做视频编解码工作,找了很多博客对编译方法描述都不全,花了一天时间自己折腾编译通过了,写篇比较完整的博客分享给大家,希望对大家有所帮助,另外,感谢其他博主的分享!一,源码包下载1.ffmpeg下载下载地址:https://ffmpeg.org(1)在主页面中找到ffmpeg5.0版本点击(2)点击下载,这里我下载的是gzip包2,下载x264代码下载地址:x264, the best H.2..._ffmpeg5.0
文章浏览阅读2.1w次,点赞118次,收藏586次。空洞卷积(膨胀卷积)的相关知识以及使用建议(HDC原则)_空洞卷积
文章浏览阅读1.6k次。python实现对excel数据某列提取文件名,匹配文件夹提取对应文件_利用python从excel表中读取文件名称再去本地提取文件
文章浏览阅读916次。以下不作为机器学习/算法工程师的学习路径,只是汇总的校招机器学习/算法工程师面试考点(因为还有笔试考点,后面结合在一起给大家学习路径),后续会为大家更新10w+字数的机器学习/算法工程师校招面试题库,还有其他岗位的相关题库和资料,想要什么岗位的可以留言哦~ 本篇根据各个公司的面试问的问题的大数据进行总结,后面还会更新面试中考察所占比例,当然,本文只包括技术面,不太包括hr面或者一些其他谈人生理..._sklearn dbscan kmeans isodata
文章浏览阅读2.9w次。1. 大英帝国 面积:三千三百一十万平方公里 年代:1946 人口:五亿三千一百万大英帝国,是一个以英国(实际仍为王国)为中心的全球帝国,在20世纪初的鼎盛时期,全世界有大约4至5亿人,也就意味着当时全球人口的约四分之一,都是该帝国的子民,其领土面积则有约3367万平方公里(它宣称对加拿大北极圈内、澳大利亚内陆和南极洲的土地拥有主权),是世界陆地总面积的四分之一,成为了历史上跨度最广、面积最大_恺撒疆域版图为多少万平方公里