Hutool是一個小而全的Java工具類庫,通過靜態方法封裝,降低相關API的學習成本,提高工作效率,使Java擁有函數式語言般的優雅,讓Java語言也可以“甜甜的”。
官方地址:https://hutool.cn/docs/#/
郵件文檔地址:https://hutool.cn/docs/#/extra/%E9%82%AE%E4%BB%B6%E5%B7%A5%E5%85%B7-MailUtil
在開始之前我們需要申請開通 POP3/SMTP 服務或者 IMAP/SMTP服務:開通 POP3/SMTP 服務或者 IMAP/SMTP服務
一、添加依賴
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.3.4</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
二、添加配置文件
在classpath(在標準Maven項目中爲src/main/resources)的config目錄下新建mail.setting文件。
配置如下:
# 郵件服務器的SMTP地址
host = smtp.163.com
# 郵件服務器的SMTP的端口
port = 465
# 發件人(必須正確,否則發送失敗)
from = [email protected]
# 用戶名(注意:如果使用foxmail郵箱,此處user爲qq號)
user = 2333
# 密碼
pass = TSCBBFHCAUTGEBSA
#使用 STARTTLS安全連接,STARTTLS是對純文本通信協議的擴展。
starttlsEnable = true
三、編寫開發代碼
import cn.hutool.core.collection.CollUtil;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
@RestController
public class MailController {
/**
* 發送單個郵件
* @return
*/
@GetMapping("/sendSingleMail")
public String sendSingleMail(){
MailUtil.send("[email protected]", "單個郵件的標題", "郵件的內容", false);
return "發送成功";
}
/**
* 發送批量郵件
* @return
*/
@GetMapping("/sendBatchMail")
public String sendBatchMail(){
ArrayList<String> tos = CollUtil.newArrayList(
"[email protected]",
"[email protected]");
MailUtil.send(tos, "批量郵件的標題", "郵件的內容", false);
return "發送成功";
}
}
發送郵件非常簡單,只需一個方法即可搞定其中按照參數順序說明如下:
- tos: 對方的郵箱地址,可以是單個,也可以是多個(Collection表示)
- subject:標題
- content:郵件正文,可以是文本,也可以是HTML內容
- isHtml: 是否爲HTML,如果是,那參數3識別爲HTML內容
- files: 可選:附件,可以爲多個或沒有,將File對象加在最後一個可變參數中即可
四、驗證結果
(1)訪問單個發送接口:http://127.0.0.1:8082/sendSingleMail
(2)訪問批量發送接口:http://127.0.0.1:8082/sendBatchMail