Spring Boot实战系列-----------邮件发送
快速导航
添加maven依赖
在Spring Boot
项目的pom.xml
文件中引入spring-boot-starter-email
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-email</artifactId>
<scope>email</scope>
</dependency>
复制代码
模版邮件需要引入 spring-boot-starter-thymeleaf
插件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
复制代码
配置文件增加邮箱相关配置
163邮箱配置,注意要替换自己的账户信息,password为授权码。
application.yml
spring:
mail:
host: smtp.163.com
username: your163account@163.com
password: your163password
default-encoding: utf-8
复制代码
QQ邮箱发送邮件配置,以下password为授权码
spring:
mail:
host: smtp.qq.com
username: yourqqaccount@qq.com
password: yourQQpassword
复制代码
项目构建
基于上节单元测试chapter5-1代码示例基础之上编写
业务层代码
service目录下创建MailService.java文件,负责业务层邮件发送功能编写
让我们利用Spring提供的JavaMailSender
接口实现邮件发送,在项目中使用到地方用@Autowired
注入邮件发送对象
MailService.java
package com.angelo.service;
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 javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class MailService {
@Value("${spring.mail.username}")
private String from;
@Autowired // 项目启动时将mailSender注入
private JavaMailSender javaMailSender;
// ... 下面会一一介绍 ...
}
复制代码
单元测试层代码
test测试目录下创建MailServiceTest.java
测试类,对业务层代码进行单元测试
MailServiceTest.java
package com.angelo.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.lang.reflect.Array;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService mailService;
@Resource
TemplateEngine templateEngine;
String to = "your163password@163.com";
// ... 下面为一一介绍 ...
}
复制代码
五种邮件发送类型讲解
文本邮件
SimpleMailMessage
封装了简单邮件的发送、接收功能、监测异常模块功能,这也是最简单的一种邮件发送,创建一个邮件消息对象,设置邮件的发送者、发送对象、邮件主题、邮件内容。
- 业务层
MailService.java
/**
* 发送文本邮件
* @param to
* @param subject
* @param content
*/
public void sendTextMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to); // 发送对象
message.setSubject(subject); // 邮件主题
message.setText(content); // 邮件内容
message.setFrom(from); // 邮件的发起者
javaMailSender.send(message);
}
复制代码
对以上业务代码进行单元测试,查看下效果
- 单元测试层
MailServiceTest.java
@Test
public void sendTextEmailTest() {
mailService.sendTextMail(to, "发送文本邮件", "hello,这是Spring Boot发送的一封文本邮件!");
}
复制代码
- 测试结果
html邮件
基于MimeMessageHelper
创建helper
对象,设置setText第二个参数为true,将会使用html格式打印邮件。
- 业务层
MailService.java
/**
* 发送HTMl邮件
* @param to
* @param subject
* @param content
* @throws MessagingException
*/
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
javaMailSender.send(message);
}
复制代码
- 单元测试层
MailServiceTest.java
@Test
public void sendHtmlEmailTest() throws MessagingException {
String content = "<html>" +
"<body>" +
"<h1 style=\"" + "color:red;" + "\">hello,这是Spring Boot发送的一封HTML邮件</h1>" +
"</body></html>";
mailService.sendHtmlMail(to, "发送HTML邮件", content);
}
复制代码
- 测试结果
可以看到邮件结果使用了例子中预先设置好的邮件格式
附件邮件
- 业务层
MailService.java
/**
* 发送带附件的邮件
* @param to
* @param subject
* @param content
* @param filePathList
* @throws MessagingException
*/
public void sendAttachmentMail(String to, String subject, String content, String[] filePathList) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
for (String filePath: filePathList) {
System.out.println(filePath);
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
String fileName = fileSystemResource.getFilename();
helper.addAttachment(fileName, fileSystemResource);
}
javaMailSender.send(message);
}
复制代码
filePathList
写上你的附件文件路径,数组格式。
- 单元测试层
MailServiceTest.java
@Test
public void sendAttachmentEmailTest() throws MessagingException {
String[] filePathList = new String[2];
filePathList[0] = "/SpringBoot-WebApi/chapter4.zip";
filePathList[1] = "/SpringBoot-WebApi/chapter5.zip";
mailService.sendAttachmentMail(to, "发送附件邮件", "hello,这是Spring Boot发送的一封附件邮件!", filePathList);
}
复制代码
- 测试结果
html内嵌图片邮件
也是基于html邮件发送,通过内嵌图片等静态资源,可以直接看到图片。
- 业务层
MailService.java
/**
* 发送html内嵌图片的邮件
* @param to
* @param subject
* @param content
* @param srcPath
* @param srcId
* @throws MessagingException
*/
public void sendHtmlInlinePhotoMail(String to, String subject, String content, String srcPath, String srcId) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource fileSystemResource = new FileSystemResource(new File(srcPath));
helper.addInline(srcId, fileSystemResource);
javaMailSender.send(message);
}
复制代码
以下单元测试中srcPath为您的本地图片路径,srcId要和上面业务层的helper.addInline(srcId, fileSystemResource)
srcId保持一致。
- 单元测试层
MailServiceTest.java
@Test
public void sendHtmlInlinePhotoMailTest() throws MessagingException {
String srcPath = "/SpringBoot-WebApi/chapter6/img/pic18.jpg";
String srcId = "pic18";
String content = "<html>" +
"<body>" +
"<h2>hello,这是Spring Boot发送的一封HTML内嵌图片的邮件</h2>" +
"<img src=\'cid:"+ srcId +"\'></img>" +
"</body></html>";
mailService.sendHtmlInlinePhotoMail(to, "发送图片邮件", content, srcPath, srcId);
}
复制代码
- 测试结果
模板邮件
邮件内容相对简单的情况下,我们可以选择使用以上几种简单邮件发送方法,在复杂业务中需要用到html结构,且html里的数据还需要动态修改,还是选择模版邮件,可以使用
Freemarker
、thymeleaf
等模板引擎,这里主要介绍使用thymeleaf
。
- 邮件模板编写
resources/templates
目录下新建emailTemplate.html
文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>模板邮件</title>
</head>
<body>
您好,<span th:text="${username}"></span>,欢迎访问我的个人博客:
<a href="https://github.com/Q-Angelo/summarize">Github</a>、
<a th:href="@{https://www.imooc.com/u/{id}(id=${id})}" href="#">慕课网</a>
</body>
</html>
复制代码
利用上面介绍的发送html邮件即可,在单元测试文件中增加一个方法进行测试。
- 单元测试层
MailServiceTest.java
@Test
public void testTemplateEmailTest() throws MessagingException {
Context context = new Context();
context.setVariable("username", "张三");
context.setVariable("id", "2667395");
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail(to, "发送模板邮件", emailContent);
}
复制代码
- 测试结果
常见问题
出现这个错误的原因是网易将我发送的邮件当成了垃圾邮件,<<发送163文本邮件>>这是我填写的邮件标题,后来发现网易是对标题里面含了163
导致的,大家遇到类似问题多检查下。
com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp10,DsCowADH1MxWegtcyxFjDw--.48939S2 1544256086
复制代码
如遇到什么问题可在下方评论区提问
作者:五月君
链接:www.imooc.com/article/267…
来源:慕课网
Github: Spring Boot实战系列
作者:五月君
链接:https://juejin.im/post/5c198ddff265da611801a465
Spring Boot实战系列-----------邮件发送的更多相关文章
- Spring Boot实战系列(7)集成Consul配置中心
本篇主要介绍了 Spring Boot 如何与 Consul 进行集成,Consul 只是服务注册的一种实现,还有其它的例如 Zookeeper.Etcd 等,服务注册发现在微服务架构中扮演这一个重要 ...
- Spring Boot Mail 实现邮件发送
此 demo 主要演示了 Spring Boot 如何整合邮件功能,包括发送简单文本邮件. 邮件服务在开发中非常常见,比如用邮件注册账号.邮件作为找回密码的途径.用于订阅内容定期邮件推送等等,下面就简 ...
- Spring Boot进阶系列一
笔者最近在总结一个 Spring Boot实战系列,以方便将来查找和公司内部培训用途. 1.Springboot从哪里来 SpringBoot是由Pivotal团队在2013年开始研发.2014年4月 ...
- 《Spring Boot 实战纪实》之前言
目录 前言 (思维篇)人人都是产品经理 1.需求文档 1.1 需求管理 1.2 如何攥写需求文档 1.3 需求关键点文档 2 原型设计 2.1 缺失的逻辑 2.2 让想法跃然纸上 3 开发设计文档 3 ...
- spring boot实战(第十二篇)整合RabbitMQ
前言 最近几篇文章将围绕消息中间件RabbitMQ展开,对于RabbitMQ基本概念这里不阐述,主要讲解RabbitMQ的基本用法.Java客户端API介绍.spring Boot与RabbitMQ整 ...
- 【转】Spring Boot干货系列:(二)配置文件解析
转自:Spring Boot干货系列:(二)配置文件解析 前言 上一篇介绍了Spring Boot的入门,知道了Spring Boot使用"习惯优于配置"(项目中存在大量的配置,此 ...
- spring boot实战(第一篇)第一个案例
版权声明:本文为博主原创文章,未经博主允许不得转载. 目录(?)[+] spring boot实战(第一篇)第一个案例 前言 写在前面的话 一直想将spring boot相关内容写成一个系列的 ...
- [转] Spring Boot实战之Filter实现使用JWT进行接口认证
[From] http://blog.csdn.net/sun_t89/article/details/51923017 Spring Boot实战之Filter实现使用JWT进行接口认证 jwt(j ...
- Spring Boot实战之定制URL匹配规则
本文首发于个人网站:Spring Boot实战之定制URL匹配规则 构建web应用程序时,并不是所有的URL请求都遵循默认的规则.有时,我们希望RESTful URL匹配的时候包含定界符". ...
随机推荐
- C++学习 内存模型和名称空间
1.单独编译 C++鼓励程序员将组件函数放在独立的文件中,如果只修改了一个文件,则可以只重新编译该文件,然后将它与其他文件的编译版本链接. 一般非常有用的组织程序的策略是把程序分成三部分: 头文件:包 ...
- NO.3:自学tensorflow之路------MNIST识别,神经网络拓展
引言 最近自学GRU神经网络,感觉真的不简单.为了能够快速跑完程序,给我的渣渣笔记本(GT650M)也安装了一个GPU版的tensorflow.顺便也更新了版本到了tensorflow-gpu 1.7 ...
- LeetCode 633. 平方数之和
题目: 给定一个非负整数 c ,你要判断是否存在两个整数 a 和 b,使得 a2 + b2 = c. 示例1: 输入: 5 输出: True 解释: 1 * 1 + 2 * 2 = 5 示例2 ...
- hadoop-2.7.2 分布式集群搭建
1.机器信息 五台centos 64位机器 2.集群规划 Server Name Hadoop Cluster Zookeeper Ensemble HBase Cluster Hadoop01 ...
- hibernate 创建工厂类
package cn.hibernate; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; / ...
- [Docker基础]如何清除不用的资源
Docker - How to cleanup resources 有时你可能需要清理Docker中不用的资源,特别是在学习Docker过程中创建的镜像.容器.网络.存储卷等. delete volu ...
- [转帖]DRAM芯片战争,跨越40年的生死搏杀
DRAM芯片战争,跨越40年的生死搏杀 超级工程一览 ·2017-08-20 12:50·半导体行业观察 阅读:1.4万 来源:内容来自超级工程一览 , 谢谢. DRAM是动态随机存储器的意思,也就是 ...
- 怎么判断pagecontrol下的TabSheet是否打开还是关闭求答案
if pagecontrol.activepage=TabSheet1 then是在当前显示页------解决方案------------------------------------------- ...
- Java获取当前运行方法所在的类和方法名
很简单,直接看代码: public void showClassAndMethod() { System.out.println(this.getClass().getSimpleName() + & ...
- 题解 P5239 【回忆京都】
你们这些写题解的,就不能把话说清楚嘛!(吐槽1) 你们这些出题的,就不能多出点东方嘛!(吐槽2) 你们这些做题的,就不来写一篇详细一点的题解嘛!(吐槽3) 以上均是个人吐槽,纯属吐槽,不带任何针对性和 ...