SpringBoot加email服务,你说有没有搞头?
Posted 跟着小苏不加班
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot加email服务,你说有没有搞头?相关的知识,希望对你有一定的参考价值。
1. 开启邮箱POP3/SMTP服务登录qq邮箱后,点击左上方的设置,选择账户,如下图。
然后一直往下滑,看到如下图的POP3/SMTP服务,点击开启,会让帮定的密保手机号发个[短信]到指定号码,然后会收到一个授权码,这个授权码在appliction.properties配置中会用到,一定要好好保存,开启后如下图
2. springboot项目添加依赖创建springboot项目,添加email依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
我的依赖如下:
<dependencies>3. 配置文件
<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>
######qq邮箱########4. 邮件服务操作类
#协议
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
springboot引用模块都通常都提供一个xxxTmplate,方便我们开发,我们可以封装一个EmailTmplate
package com.ljw.task.config;5. 测试类
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);
}
}
}
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
helloTemplate.html:
<!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
avatar.jpg:
这里就不贴测试发送邮件的截图,发送人和接收人换成自己邮箱,自己测试下就行。
6. 常用业务分析- 用户注册后需要激活账号才能使用的场景:
用户注册成功,保存数据到redis,设置过期时间,并发送邮件信息到指定邮箱,该邮件含有用户唯一标识的key的超链接,用户点击该超链接则回访到我们的激活接口,验证信息正确则激活。如在设定时间内没有点击激活则激活失败。
2.其他需要通知的场景
有些字在这里属于敏感词汇,所以会有错别字,大家多担待
以上是关于SpringBoot加email服务,你说有没有搞头?的主要内容,如果未能解决你的问题,请参考以下文章
UDS 14229 -1 刷写34,36,37服务,标准加Trace讲解,没理由搞不明白