本文主要是介绍Spring Boot + JavaMailSender + Thymeleaf实现服务端发送邮件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Spring Boot-实现邮件发送
What-什么是邮件服务
邮件服务在互联网早期就已经出现,如今已成为人们互联网生活中必不可少的一项服务。那么邮件服务是怎么工作的呢?如下给出邮件发送与接收的典型过程:
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客户端,然后让客户端发送邮件到服务器。
Why-为什么系统要建立邮件服务
电子邮件具有全世界通用的协议。所以你可以使用任何一种邮件的客户端,以任何一种方式去查看你的邮件。这个世界上的电子邮件客户端不下千种,他们都以不同的方式去满足了不同需求的人群,邮件有以下特点:
① 企业内部的沟通,邮件服务还是被认为“正式”的,比即时通信“可靠”。
② 支持转发/抄送,公开的,统一的通信协议,能够存档。
Why-如何实现邮件服务
- 配置邮件服务器
开启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
spring.mail.username=javalsj@163.com
# 邮箱开启的授权码
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
- 编写发送邮件工具JavaMailUtil代码,支持发送纯文本邮件、html邮件、附件邮件、thymeleaf模板邮件类型。
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邮件发送器*/@Autowiredprivate JavaMailSender mailSender;/*** thymeleaf模板引擎*/@Autowiredprivate TemplateEngine templateEngine;/*** 发送不含附件,且不含嵌入html静态资源页面的纯文本简单邮件* * @param deliver* 发送人邮箱名 如: javalsj@163.com* @param receiver* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopy* 抄送人,可多个抄送人 如:33333@sohu.com* @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* 发送人邮箱名 如: javalsj@163.com* @param receivers* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopys* 抄送人,可多个抄送人 如:3333@sohu.com* @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* 发送人邮箱名 如: javalsj@163.com* @param receivers* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopys* 抄送人,可多个抄送人 如:3333@sohu.com.cn* @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* 发送人邮箱名 如: javalsj@163.com* @param receivers* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopys* 抄送人,可多个抄送人 如:33333@jiuqi.com.cn* @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* 发送人邮箱名 如: javalsj@163.com* @param receivers* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopys* 抄送人,可多个抄送人 如:33333@sohu.com* @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* 发送人邮箱名 如: javalsj@163.com* @param receivers* 收件人,可多个收件人 如:11111@qq.com,2222@163.com* @param carbonCopys* 抄送人,可多个抄送人 如:3333@sohu.com* @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")@ResponseBodypublic Result sendSimpleEmail() {Result result;try {javaMailUtil.sendSimpleEmail("javalsj@163.com", new String[] { "1111@qq.com", "2222@qq.com" },new String[] { "33333@sohu.com" }, "您收到一封高大上的邮件,请查收。", "测试邮件逗你玩的。");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")@ResponseBodypublic 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("javalsj@163.com", new String[] { "11111@qq.com", "22222@qq.com" },new String[] { "3333@sohu.com" }, "您收到一封高大上的邮件,请查收。",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的单独配置。
这篇关于Spring Boot + JavaMailSender + Thymeleaf实现服务端发送邮件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!