SpringBoot加email服务,你说有没有搞头? Sp

SpringBoot加email服务,你说有没有搞头?

「这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战

  1. 开启邮箱POP3/SMTP服务

登录qq邮箱后,点击左上方的设置,选择账户,如下图。

1637150849(1).png

然后一直往下滑,看到如下图的POP3/SMTP服务,点击开启,会让帮定的密保手机号发个[短信]到指定号码,然后会收到一个授权码,这个授权码在appliction.properties配置中会用到,一定要好好保存,开启后如下图

image.png

  1. springboot项目添加依赖

创建springboot项目,添加email依赖

1
2
3
4
xml复制代码<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

我的依赖如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
xml复制代码<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.5.3</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

<!-- 模板引擎,发送模板邮件用到 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

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

</dependencies>
  1. 配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
properties复制代码######qq邮箱########
#协议
spring.mail.protocol=smtp
#邮箱服务器地址
spring.mail.host=smtp.qq.com
#邮箱服务器地址
spring.mail.username=xxx@qq.com
#这里的password不是登录密码,是开启POP3之后设置的客户端授权码
#邮箱密码,开启POP3/SMTP服务时会有给你
spring.mail.password=自己POP3/SMTP服务密码
#编码格式
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
##默认端口25,使用465端口时,需要添加配置:
spring.mail.port=465
spring.mail.properties.mail.smtp.ssl.enable=true
  1. 邮件服务操作类

springboot引用模块都通常都提供一个xxxTmplate,方便我们开发,我们可以封装一个EmailTmplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
java复制代码package com.ljw.task.config;

import lombok.Getter;
import org.springframework.boot.autoconfigure.mail.MailProperties;
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 org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.IContext;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
* @Description: 邮件操作类
* @Author: jianweil
* @date: 2021/11/19 15:07
*/
@Service
@Getter
public class EmailTemplate {

@Resource
private JavaMailSender javaMailSender;

@Resource
private TemplateEngine templateEngine;

//@Resource
//private MailProperties mailProperties;

/**
* 发送简单文本邮件
*
* @param from 发送者邮箱
* @param to 接受者邮箱
* @param subject 邮件主题
* @param text 邮件内容
*/
public void sendTextMail(String from, String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
// 发送者
message.setFrom(from);
// 接收者
message.setTo(to);
//邮件主题
message.setSubject(subject);
// 邮件内容
message.setText(text);
javaMailSender.send(message);
}


/**
* 发送Html邮件
*
* @param from 发送者邮箱
* @param to 接受者邮箱
* @param subject 邮件主题
* @param html 邮件内容 带html标签
*/
public void sendHtmlMail(String from, String to, String subject, String html) {
try {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(html, true);
javaMailSender.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Messaging Exception !", e);
}
}


/**
* 发送附件邮件
*
* @param from 发送者邮箱
* @param to 接受者邮箱
* @param subject 邮件主题
* @param text 邮件内容
* @param attachmentFilename 附件名称
* @param file 附件
*/
public void sendAttachmentMail(String from, String to, String subject, String text, String attachmentFilename, FileSystemResource file) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
//加入邮件
helper.addAttachment(attachmentFilename, file);
javaMailSender.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Messaging Exception !", e);
}
}

/**
* 发送内联资源邮件
*
* @param from 发送者邮箱
* @param to 接受者邮箱
* @param subject 邮件主题
* @param text 邮件内容,包含内联文件id 如: String text = "<html><body>宫崎骏电影图片:<img src='cid:" + contentId + "' ></body></html>";
* @param contentId 内联文件id
* @param file 文件
*/
public void sendInlineResourceMail(String from, String to, String subject, String text, String contentId, FileSystemResource file) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, true);
helper.addInline(contentId, file);
javaMailSender.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Messaging Exception !", e);
}
}

/**
* 发送模板邮件
*
* @param from 发送者邮箱
* @param to 接受者邮箱
* @param subject 邮件主题
* @param context 内容类,和模板匹配参数,如下配置id参数的值为myvaluesitest:
* Context context = new Context();
* context.setVariable("id","myvaluesitest");
* @param template templates目录下的模板文件名,如templates/emailTemplate.html则传:emailTemplate
*/
public void sendTemplateMail(String from, String to, String subject, IContext context, String template) {
MimeMessage message = javaMailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
String text = templateEngine.process(template, context);
helper.setText(text, true);
javaMailSender.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Messaging Exception !", e);
}
}

}
  1. 测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
java复制代码package com.ljw.task.config;

import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.FileSystemResource;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.io.File;

/**
* @Description: todo
* @Author: jianweil
* @date: 2021/11/21 18:45
*/
@SpringBootTest
class EmailTemplateTest {

@Resource
private EmailTemplate emailTemplate;
@Resource
private MailProperties mailProperties;

public String getSender() {
return mailProperties.getUsername();
}

public String getReceiver() {
return mailProperties.getUsername();
}

/**
* 文本
*/
@Test
void sendTextMail() {
emailTemplate.sendTextMail(getSender(), getReceiver(), "标题:sendTextMail", "文本内容");
}

/**
* 带html标签
*/
@Test
void sendHtmlMail() {
StringBuffer sb = new StringBuffer();
sb.append("<h1>大标题-h1</h1>")
.append("<p style='color:#F00'>红色字</p>")
.append("<p style='text-align:right'>右对齐</p>");
emailTemplate.sendHtmlMail(getSender(), getReceiver(), "标题:sendHtmlMail", sb.toString());
}

/**
* 带附件
*/
@Test
void sendAttachmentMail() {
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
emailTemplate.sendAttachmentMail(getSender(), getReceiver(), "标题:sendAttachmentMail", "我发了一个附件给你注意查收", "附件名.jpg", file);
}

/**
* 发送内联资源邮件
*/
@Test
void sendInlineResourceMail() {
String imgId = "avatar";
String content = "<html><body>宫崎骏电影图片:<img src='cid:" + imgId + "' ></body></html>";
FileSystemResource res = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
emailTemplate.sendInlineResourceMail(getSender(), getReceiver(), "标题:sendInlineResourceMail", content, imgId, res);
}

/***
* 发送模板邮件
*/
@Test
void sendTemplateMail() {
Context context = new Context();
context.setVariable("id", "hello");
emailTemplate.sendTemplateMail(getSender(), getReceiver(), "标题:sendTemplateMail", context, "helloTemplate");
}
}

发送模板邮件用到的模板类:helloTemplate.html

image.png
helloTemplate.html:

1
2
3
4
5
6
7
8
9
10
11
java复制代码<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>模板邮件</title>
</head>
<body>
您好,这是模板邮件,请点击下面的链接完成跳转,
<a href="#" th:href="@{'http://www.baidu.com/s?wd='+${id}}">跳转百度</a> <a th:text=" ${id}"></a>。
</body>
</html>

发送附件用到的图片:avatar.jpg

image.png
avatar.jpg:
avatar.jpg

这里就不贴测试发送邮件的截图,发送人和接收人换成自己邮箱,自己测试下就行。

  1. 常用业务分析

  1. 用户注册后需要激活账号才能使用的场景:

用户注册成功,保存数据到redis,设置过期时间,并发送邮件信息到指定邮箱,该邮件含有用户唯一标识的key的超链接,用户点击该超链接则回访到我们的激活接口,验证信息正确则激活。如在设定时间内没有点击激活则激活失败。

  1. 其他需要通知的场景

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%