1. 開(kāi)啟郵箱POP3/SMTP服務(wù)
登錄qq郵箱后,點(diǎn)擊左上方的設(shè)置讨惩,選擇賬戶辟癌,如下圖。
然后一直往下滑步脓,看到如下圖的POP3/SMTP服務(wù)愿待,點(diǎn)擊開(kāi)啟,會(huì)讓幫定的密保手機(jī)號(hào)發(fā)個(gè)[短信]到指定號(hào)碼靴患,然后會(huì)收到一個(gè)授權(quán)碼仍侥,這個(gè)授權(quán)碼在appliction.properties配置中會(huì)用到,一定要好好保存鸳君,開(kāi)啟后如下圖
2. springboot項(xiàng)目添加依賴
創(chuàng)建springboot項(xiàng)目农渊,添加email依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
我的依賴如下:
<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>
<!-- 模板引擎,發(fā)送模板郵件用到 -->
<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>
3. 配置文件
######qq郵箱########
#協(xié)議
spring.mail.protocol=smtp
#郵箱服務(wù)器地址
spring.mail.host=smtp.qq.com
#郵箱服務(wù)器地址
spring.mail.username=xxx@qq.com
#這里的password不是登錄密碼,是開(kāi)啟POP3之后設(shè)置的客戶端授權(quán)碼
#郵箱密碼或颊,開(kāi)啟POP3/SMTP服務(wù)時(shí)會(huì)有給你
spring.mail.password=自己POP3/SMTP服務(wù)密碼
#編碼格式
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
##默認(rèn)端口25砸紊,使用465端口時(shí),需要添加配置:
spring.mail.port=465
spring.mail.properties.mail.smtp.ssl.enable=true
4. 郵件服務(wù)操作類
springboot引用模塊都通常都提供一個(gè)xxxTmplate囱挑,方便我們開(kāi)發(fā)醉顽,我們可以封裝一個(gè)EmailTmplate
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;
/**
* 發(fā)送簡(jiǎn)單文本郵件
*
* @param from 發(fā)送者郵箱
* @param to 接受者郵箱
* @param subject 郵件主題
* @param text 郵件內(nèi)容
*/
public void sendTextMail(String from, String to, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
// 發(fā)送者
message.setFrom(from);
// 接收者
message.setTo(to);
//郵件主題
message.setSubject(subject);
// 郵件內(nèi)容
message.setText(text);
javaMailSender.send(message);
}
/**
* 發(fā)送Html郵件
*
* @param from 發(fā)送者郵箱
* @param to 接受者郵箱
* @param subject 郵件主題
* @param html 郵件內(nèi)容 帶html標(biāo)簽
*/
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);
}
}
/**
* 發(fā)送附件郵件
*
* @param from 發(fā)送者郵箱
* @param to 接受者郵箱
* @param subject 郵件主題
* @param text 郵件內(nèi)容
* @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);
}
}
/**
* 發(fā)送內(nèi)聯(lián)資源郵件
*
* @param from 發(fā)送者郵箱
* @param to 接受者郵箱
* @param subject 郵件主題
* @param text 郵件內(nèi)容,包含內(nèi)聯(lián)文件id 如: String text = "<html><body>宮崎駿電影圖片:<img src='cid:" + contentId + "' ></body></html>";
* @param contentId 內(nèi)聯(lián)文件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);
}
}
/**
* 發(fā)送模板郵件
*
* @param from 發(fā)送者郵箱
* @param to 接受者郵箱
* @param subject 郵件主題
* @param context 內(nèi)容類平挑,和模板匹配參數(shù)游添,如下配置id參數(shù)的值為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);
}
}
}
5. 測(cè)試類
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(), "標(biāo)題:sendTextMail", "文本內(nèi)容");
}
/**
* 帶html標(biāo)簽
*/
@Test
void sendHtmlMail() {
StringBuffer sb = new StringBuffer();
sb.append("<h1>大標(biāo)題-h1</h1>")
.append("<p style='color:#F00'>紅色字</p>")
.append("<p style='text-align:right'>右對(duì)齊</p>");
emailTemplate.sendHtmlMail(getSender(), getReceiver(), "標(biāo)題:sendHtmlMail", sb.toString());
}
/**
* 帶附件
*/
@Test
void sendAttachmentMail() {
FileSystemResource file = new FileSystemResource(new File("src/main/resources/static/images/avatar.jpg"));
emailTemplate.sendAttachmentMail(getSender(), getReceiver(), "標(biāo)題:sendAttachmentMail", "我發(fā)了一個(gè)附件給你注意查收", "附件名.jpg", file);
}
/**
* 發(fā)送內(nèi)聯(lián)資源郵件
*/
@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(), "標(biāo)題:sendInlineResourceMail", content, imgId, res);
}
/***
* 發(fā)送模板郵件
*/
@Test
void sendTemplateMail() {
Context context = new Context();
context.setVariable("id", "hello");
emailTemplate.sendTemplateMail(getSender(), getReceiver(), "標(biāo)題:sendTemplateMail", context, "helloTemplate");
}
}
發(fā)送模板郵件用到的模板類:helloTemplate.html
helloTemplate.html:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>模板郵件</title>
</head>
<body>
您好,這是模板郵件,請(qǐng)點(diǎn)擊下面的鏈接完成跳轉(zhuǎn),
<a href="#" th:href="@{'http://www.baidu.com/s?wd='+${id}}">跳轉(zhuǎn)百度</a> <a th:text=" ${id}"></a>通熄。
</body>
</html>
發(fā)送附件用到的圖片:avatar.jpg
avatar.jpg:
這里就不貼測(cè)試發(fā)送郵件的截圖唆涝,發(fā)送人和接收人換成自己郵箱,自己測(cè)試下就行唇辨。
6. 常用業(yè)務(wù)分析
- 用戶注冊(cè)后需要激活賬號(hào)才能使用的場(chǎng)景:
用戶注冊(cè)成功廊酣,保存數(shù)據(jù)到redis,設(shè)置過(guò)期時(shí)間赏枚,并發(fā)送郵件信息到指定郵箱亡驰,該郵件含有用戶唯一標(biāo)識(shí)的key的超鏈接,用戶點(diǎn)擊該超鏈接則回訪到我們的激活接口嗡贺,驗(yàn)證信息正確則激活隐解。如在設(shè)定時(shí)間內(nèi)沒(méi)有點(diǎn)擊激活則激活失敗。
2.其他需要通知的場(chǎng)景
作者:小伙子vae
鏈接:
https://juejin.cn/post/7033215143081148424