介绍

邮件服务是常用的服务之一,作用很多,对外可以给用户发送活动、营销广告等;对内可以发送系统监控报告与告警。

本文将介绍Springboot如何整合邮件服务,并给出不同邮件服务商的整合配置。

如图所示:

 
Springboot整合邮件服务

开发过程

Springboot搭建

Springboot的搭建非常简单,我们使用 Spring Initializr来构建,十分方便,选择需要用到的模块,就能快速完成项目的搭建:

 
Spring Initializr

引入依赖

为了使用邮件服务,我们需要引入相关的依赖,对于Springboot加入下面的依赖即可:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

配置文件

需要配置邮件服务提供商的相关参数,如服务地址、用户名及密码等。下面的例子是QQ的配置,其中密码并不是QQ密码,而是QQ授权码,后续我们再讲怎么获得。

Springboot的配置文件application.yml如下:

server:
port: 8080
spring:
profiles:
active: qq
---
spring:
profiles: qq
mail:
host: smtp.qq.com
username: xxx@qq.com
password: xxx
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
---
spring:
profiles: netEase
mail:
host: smtp.163.com
username: xxx@163.com
password: xxx
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true

实现发送服务

将JavaMailSender注入,组装Message后,就可以发送最简单的文本邮件了。

@Autowired
private JavaMailSender emailSender; public void sendNormalText(String from, String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(text);
emailSender.send(message);
}

调用接口

服务调用实现后,通过Controller对外暴露REST接口,具体代码如下:

@Value("${spring.mail.username}")
private String username;
@Autowired
private MailService mailService; @GetMapping("/normalText")
public Mono<String> sendNormalText() {
mailService.sendNormalText(username, username,
"Springboot Mail(Normal Text)",
"This is a mail from Springboot!");
return Mono.just("sent");
}

把实现的MailService注入到Controller里,调用对应的方法即可。本次的邮件发送人和收件人都是同一个帐户,实际实现可以灵活配置。

通过Postman调用接口来测试一下能不能正常发送:

 
Postman

成功返回"sent",并收到了邮件,测试通过。

多种类型邮件

简单文本邮件

简单文本邮件如何发送,刚刚已经讲解,不再赘述。

HTML邮件

纯文本虽然已经能满足很多需求,但很多时候也需要更加丰富的样式来提高邮件的表现力。这时HTML类型的邮件就非常有用。

Service代码如下:

public void sendHtml(String from, String to, String subject, String text) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
emailSender.send(message);
}

与简单的文本不同的是,本次用到了MimeMessageMimeMessageHelper,这是非常有用的类,后续我们经常会用到,组合使用能大大丰富邮件表现形式。

Controller的代码如下:

@GetMapping("/html")
public Mono<String> sendHtml() throws MessagingException {
mailService.sendHtml(username, username,
"Springboot Mail(HTML)",
"<h1>This is a mail from Springboot!</h1>");
return Mono.just("sent");
}

带附件邮件

邮件发送文件再正常不过,发送附件需要使用MimeMessageHelper.addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)方法,第一个参数为附件名,第二参数为文件流资源。Service代码如下:

public void sendAttachment(String from, String to, String subject, String text, String filePath) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
helper.addAttachment(filePath, file);
emailSender.send(message);
}

Controller代码如下:

@GetMapping("/attachment")
public Mono<String> sendAttachment() throws MessagingException {
mailService.sendAttachment(username, username,
"Springboot Mail(Attachment)",
"<h1>Please check the attachment!</h1>",
"/Pictures/postman.png");
return Mono.just("sent");
}

带静态资源邮件

我们访问的网页其实也是一个HTML,是可以带很多静态资源的,如图片、视频等。Service代码如下:

public void sendStaticResource(String from, String to, String subject, String text, String filePath, String contentId) throws MessagingException {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
helper.addInline(contentId, file);
emailSender.send(message);
}

其中,contentId为HTML里静态资源的ID,需要对应好。

Controller代码如下:

@GetMapping("/inlinePicture")
public Mono<String> sendStaticResource() throws MessagingException {
mailService.sendStaticResource(username, username,
"Springboot Mail(Static Resource)",
"<html><body>With inline picture<img src='cid:picture' /></body></html>",
"/Pictures/postman.png",
"picture");
return Mono.just("sent");
}

模板邮件

Java的模板引擎很多,著名的有Freemarker、Thymeleaf、Velocity等,这不是本点的重点,所以只以Freemarker为例使用。

Service代码如下:

@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer; public void sendTemplateFreemarker(String from, String to, String subject, Map<String, Object> model, String templateFile) throws Exception {
MimeMessage message = emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateFile);
String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
helper.setText(html, true);
emailSender.send(message);
}

注意需要注入FreeMarkerConfigurer,然后使用FreeMarkerTemplateUtils解析模板,返回String,就可以作为内容发送了。

Controller代码如下:

@GetMapping("/template")
public Mono<String> sendTemplateFreemarker() throws Exception {
Map<String, Object> model = new HashMap<>();
model.put("username", username);
model.put("templateType", "Freemarker");
mailService.sendTemplateFreemarker(username, username,
"Springboot Mail(Template)",
model,
"template.html");
return Mono.just("sent");
}

注意模板文件template.html要放在resources/templates/目录下面,这样才能找得到。

模板内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Hello ${username}</h1>
<h1>This is a mail from Springboot using ${templateType}</h1>
</body>
</html>

其中${username}${templateType}为需要替换的变量名,Freemarker提供了很多丰富的变量表达式,这里不展开讲了。

集成不同邮件服务商

邮件服务的提供商很多,国内最常用的应该是QQ邮箱和网易163邮箱了。

QQ

集成QQ邮件需要有必备的账号,还要开通授权码。开通授权码后配置一下就可以使用了,官方的文档如下:

什么是授权码,它又是如何设置?

需要注意的是,开通授权码是需要使用绑定的手机号发短信到特定号码的,如果没有绑定手机或者绑定手机不可用,那都会影响开通。

开通之后,授权码就要以作为密码配置到文件中。

163

网易的开通方式与QQ没有太大差别,具体的指导可以看如下官方文档:

如何开启客户端授权码?

同样也是需要绑定手机进行操作。

总结

本次例子发送后收到邮件如图所示:

 
邮件

邮件功能强大,Springboot也非常容易整合。技术利器,善用而不滥用。


欢迎关注公众号<南瓜慢说>,将为你持续更新...

Springboot】Springboot整合邮件服务(HTML/附件/模板-QQ、网易)的更多相关文章

  1. SpringBoot系列九:SpringBoot服务整合(整合邮件服务、定时调度、Actuator监控)

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.概念:SpringBoot 服务整合 2.背景 在进行项目开发的时候经常会遇见以下的几个问题:需要进行邮件发送.定时的任务调 ...

  2. springboot系列九,springboot整合邮件服务、整合定时任务调度

    一.整合邮件服务 如果要进行邮件的整合处理,那么你一定需要有一个邮件服务器,实际上 java 本身提供有一套 JavaMail 组件以实现邮件服务器的搭建,但是这个搭建的服务器意义不大,因为你现在搭建 ...

  3. SpringBoot 之集成邮件服务.

    一.前言 Spring Email 抽象的核心是 MailSender 接口,MailSender 的实现能够把 Email 发送给邮件服务器,由邮件服务器实现邮件发送的功能. Spring 自带了一 ...

  4. springboot mail整合freemark实现动态生成模板

    目标:1:springboot 整合 mail2: mail 使用freemark 实现模板动态生成(就是通过字符串生成模板,不需要在工程中写入固定模板)3: springboot 整合aop 实现日 ...

  5. SpirngBoot之整合邮件服务

    一.集成邮件服务 1.1 获取客户端授权码 1.2 引入依赖 <dependencies> ...... <dependency> <groupId>org.spr ...

  6. springboot(十):邮件服务

    springboot仍然在狂速发展,才五个多月没有关注,现在看官网已经到1.5.3.RELEASE版本了.准备慢慢在写写springboot相关的文章,本篇文章使用springboot最新版本1.5. ...

  7. Springboot 系列(十三)使用邮件服务

    在我们这个时代,邮件服务不管是对于工作上的交流,还是平时的各种邮件通知,都是一个十分重要的存在.Java 从很早时候就可以通过 Java mail 支持邮件服务.Spring 更是对 Java mai ...

  8. spring-boot(六) 邮件服务

    学习文章来自:springboot(十):邮件服务 简单使用 1.pom包配置 pom包里面添加spring-boot-starter-mail包引用 <dependencies> < ...

  9. SpringBoot RabbitMQ 整合使用

    ![](http://ww2.sinaimg.cn/large/006tNc79ly1g5jjb62t88j30u00gwdi2.jpg) ### 前提 上次写了篇文章,[<SpringBoot ...

随机推荐

  1. [整理] jQuery插件开发

    1.类级别的插件开发 类级别的插件开发,可似为给jQuery类添加方法,调用方式:$.你的方法(),如:$.ajax() 函数. 1.1.给jQuery类添加方法 $.alertMsg = funct ...

  2. JAVA截取后String字符串六位字符

    public static void main(String[] args){ String cellphone="; String pwd = cellphone.substring(ce ...

  3. 浅谈ViewPager与TabLayout的简单用法

      今天介绍一下ViewPager与TabLayout的简单用法 1.准备   在一切开始之前,你懂得,先导库,老方法,在build.gradle直接添加下面这一句   implementation ...

  4. 给Xshell增加快速命令集

    一.显示快速命令栏 二.配置快速命令集 在工具中找到快速命令集 添加快速命令集 三.使用快速命令集

  5. [Linux] Linux中重命名文件和文件夹的方法(mv命令和rename命令)

    原文链接 在Linux下重命名文件或目录,可以使用mv命令或rename命令,这里分享下二者的使用方法. mv命令既可以重命名,又可以移动文件或文件夹. 例子:将目录A重命名为B mv A B 例子: ...

  6. 这些Mysql常用命令你是否还记得?

    前言 记录mysql常用命令操作 基础操作 命令行登录mysql  mysql -u用户名 -p用户密码 为表增加创建时间和更新时间 ALTER TABLE order_info_tbl ADD CO ...

  7. 暑期——第四周总结(Ubuntu系统安装新版eclipse双击无法打开问题 【已解决】)

    所花时间:7天 代码行:200(python)+3000(java) 博客量:1篇 了解到知识点 : Ubuntu安装新eclipse 在通过软件中心安装好eclipse之后,发现各种东西都不顺眼,不 ...

  8. 多源最短路径算法—Floyd算法

    前言 在图论中,在寻路最短路径中除了Dijkstra算法以外,还有Floyd算法也是非常经典,然而两种算法还是有区别的,Floyd主要计算多源最短路径. 在单源正权值最短路径,我们会用Dijkstra ...

  9. 基于djiango实现简易版的图书管理系统

    介绍: 本程序仅仅实现图书数据的增删查 树形结构如下   全部代码如下: url: from django.urls import path from front import views as fr ...

  10. CF #579 (Div. 3) E.Boxers

    E.Boxers time limit per test2 seconds memory limit per test256 megabytes inputstdin outputstdout The ...