前言
SpringBoot系列Demo代碼,實現(xiàn)郵件和短信的發(fā)送。
一、開啟服務
1.POP3和SMTP協(xié)議
Spring框架為使用JavaMailSender接口發(fā)送電子郵件提供了一個簡單的抽象,Spring Boot為它提供了自動配置以及啟動模塊。
在使用Spring Boot發(fā)送郵件之前,要開啟POP3和SMTP協(xié)議,需要獲得郵件服務器的授權(quán)碼
SMTP 協(xié)議全稱為 Simple Mail Transfer Protocol,譯作簡單郵件傳輸協(xié)議,它定義了郵件客戶端軟件與 SMTP 服務器之間,以及 SMTP 服務器與 SMTP 服務器之間的通信規(guī)則。
POP3 協(xié)議全稱為 Post Office Protocol ,譯作郵局協(xié)議,它定義了郵件客戶端與 POP3 服務器之間的通信規(guī)則
2.獲取授權(quán)碼
以QQ郵箱為例:
開啟服務之后,會獲得一個授權(quán)碼:
成功開啟POP3/SMTP服務,在第三方客戶端登錄時,密碼框請輸入以下授權(quán)碼:
二、使用步驟
1.環(huán)境配置
引入依賴
<!-- springboot 郵件mail -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--Thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
application.yml
spring:
# 數(shù)據(jù)源
datasource:
url: jdbc:mysql://localhost:3306/local_develop?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
profiles:
active: @spring.profiles.active@
# 郵件
mail:
default-encoding: utf-8
# 配置 SMTP 服務器地址
host: smtp.qq.com
#發(fā)送方郵件名
username:
#授權(quán)碼
password:
# thymeleaf模板格式
thymeleaf:
cache: false
encoding: UTF-8
mode: HTML
servlet:
content-type: text/html
prefix: classpath:/templates/
suffix: .html
2.代碼編寫
SendMail.java
@Service
public class SendMail {
private final static Logger LOGGER = LoggerFactory.getLogger(SendMail.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String sendFrom;
/**
* 發(fā)送簡單郵件
*
* @param sendTo 接收人
* @param subject 郵件主題
* @param text 郵件內(nèi)容
*/
public void sendSimpleMail(String sendTo, String subject, String text) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(sendFrom);
message.setTo(sendTo);
message.setSubject(subject);
message.setText(text);
mailSender.send(message);
}
/**
* 發(fā)送HTML格式的郵件,并可以添加附件
*
* @param sendTo 接收人
* @param subject 郵件主題
* @param content 郵件內(nèi)容(html)
* @param files 附件
* @throws MessagingException
*/
public void sendHtmlMail(String sendTo, String subject, String content, List<File> files) {
MimeMessage message = mailSender.createMimeMessage();
// true表示需要創(chuàng)建一個multipart message
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(sendFrom);
helper.setTo(sendTo);
helper.setSubject(subject);
helper.setText(content, true);
//添加附件
for (File file : files) {
helper.addAttachment(file.getName(), new FileSystemResource(file));
}
mailSender.send(message);
} catch (MessagingException e) {
LOGGER.warn("郵件發(fā)送出錯:{}", e);
}
}
}
SendMailController.java
@Api(value = "郵件發(fā)送接口", tags = "郵件發(fā)送接口")
@RestController
@RequestMapping("/index")
public class SendMailController {
@Autowired
private SendMail sendMail;
@Autowired
private TemplateEngine templateEngine;
@ApiOperation(value = "發(fā)送簡單郵件", notes = "發(fā)送簡單郵件")
@ApiImplicitParams({
@ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),
@ApiImplicitParam(name = "subject", required = false, value = "郵件主題"),
@ApiImplicitParam(name = "text", required = false, value = "郵件內(nèi)容"),
})
@GetMapping("/sendSimpleMail")
public ApiResponse sendSimpleMail(@RequestParam String sendTo,
@RequestParam(required = false) String subject,
@RequestParam(required = false) String text) {
sendMail.sendSimpleMail(sendTo, subject, text);
return ApiResponse.ok();
}
@ApiOperation(value = "發(fā)送HTML格式的郵件", notes = "使用Thymeleaf模板發(fā)送郵件")
@ApiImplicitParams({
@ApiImplicitParam(name = "sendTo", required = true, value = "接收人"),
@ApiImplicitParam(name = "subject", required = false, value = "郵件主題"),
@ApiImplicitParam(name = "content", required = true, value = "郵件模板"),
})
@GetMapping("/sendHtmlMail")
public ApiResponse sendHtmlMail(@RequestParam String sendTo,
@RequestParam(required = false) String subject,
@RequestParam String content) {
Context context = new Context();
context.setVariable("username", "xx");
context.setVariable("num", "007");
// 模板
String template = "mail/" + content;
List<File> files = new ArrayList<>();
sendMail.sendHtmlMail(sendTo, subject, templateEngine.process(template, context), files);
return ApiResponse.ok();
}
}
mail.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>hello 歡迎加入 榮華富貴 大家庭,您的入職信息如下:</p>
<table border="1">
<tr>
<td>姓名</td>
<td th:text="${username}"></td>
</tr>
<tr>
<td>工號</td>
<td th:text="${num}"></td>
</tr>
</table>
<div style="color: #ff1a0e">加油加油</div>
<div style="color: #ff1a0e">努力努力!</div>
<div style="color: #ff1a0e">今天睡地板,明天當老板!</div>
</body>
</html>
3.郵件發(fā)送測試
啟動項目,打開http://localhost:8080/doc.html
調(diào)試接口,效果如下:
4.短信發(fā)送
短信發(fā)送通過調(diào)用API實現(xiàn),具體參考:http://www.itdecent.cn/p/89b4244d516c
本文參考:http://springboot.javaboy.org/2019/0717/springboot-mail
? 上一章:SpringBoot —— 整合Logback,輸出日志到文件
? 下一章:SpringBoot —— 多線程定時任務的實現(xiàn)(注解配置、task:annotation-driven配置)
創(chuàng)作不易,關注、點贊就是對作者最大的鼓勵,歡迎在下方評論留言
求關注,定期分享Java知識,一起學習,共同成長。