在項目開發中,除了需要短信驗證外,有時候為了節省 短信費也會使用郵件發送。在Spring項目中發送郵件需要封裝復雜的消息體,不太方便。而在Spring Boot項目中發送郵件就太簡單了,下面一起來看看Spring Boot如何發送郵件。
本文以126郵箱為例進行郵件發送功能,其他郵箱的配置也都大同小異。
1. 獲取授權碼
常用的電子協議有POP3
,SMTP
,IMAP
,協議的具體區別就不進行詳細介紹了。這里選擇smtp
協議進行演示。登錄郵箱,在設置中找到協議地址,點擊開啟。授權碼只會顯示一次,需要保存好。
下面是126郵箱對應的三種協議主機地址:
2. 添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
3. 配置郵箱信息
需要注意的是password
不是郵箱登錄密碼,而是第一步中獲取的授權碼。
spring:
mail:
default-encoding: utf-8
# 主機地址
host: smtp.126.com
# 郵箱名
username: xxx@126.com
# 授權碼(不是密碼)
password: xxxxxxxxxx
4. 發送郵件
封裝SimpleMailMessage
消息內容,注入JavaMailSender
調用其send()
方法,完成郵件發送。其中收件人和抄送人支持多個發送,多個地址用,
拼接起來完成批量發送。
@RestController
public class Email {
@Autowired
private JavaMailSender mailSender;
@GetMapping("send")
private void send(){
SimpleMailMessage message = new SimpleMailMessage();
// 發件人
message.setFrom("xxx@126.com");
// 收件人
message.setTo("xxx@163.com");
// 郵件標題
message.setSubject("Java發送郵件第二彈");
// 郵件內容
message.setText("你好,這是一條用於測試Spring Boot郵件發送功能的郵件!哈哈哈~~~");
// 抄送人
message.setCc("xxx@qq.com");
mailSender.send(message);
}
}
5. 發送效果
最后一起來看看上面內容中涉及到的三個郵箱是否接收到數據了。
發件人:
收件人:
抄送人:
本文示例代碼已上傳至github,點個star
支持一下!
Spring Boot系列教程目錄
spring-boot-route(一)Controller接收參數的幾種方式
spring-boot-route(二)讀取配置文件的幾種方式
spring-boot-route(五)整合swagger生成接口文檔
spring-boot-route(六)整合JApiDocs生成接口文檔
spring-boot-route(七)整合jdbcTemplate操作數據庫
spring-boot-route(八)整合mybatis操作數據庫
spring-boot-route(九)整合JPA操作數據庫
spring-boot-route(十一)數據庫配置信息加密
spring-boot-route(十二)整合redis做為緩存
spring-boot-route(十三)整合RabbitMQ
spring-boot-route(十五)整合RocketMQ
spring-boot-route(十六)使用logback生產日志文件
spring-boot-route(十七)使用aop記錄操作日志
spring-boot-route(十八)spring-boot-adtuator監控應用
spring-boot-route(十九)spring-boot-admin監控服務
spring-boot-route(二十)Spring Task實現簡單定時任務
spring-boot-route(二十一)quartz實現動態定時任務
spring-boot-route(二十二)實現郵件發送功能
spring-boot-route(二十四)分布式session的一致性處理
spring-boot-route(二十五)兩行代碼實現國際化
spring-boot-route(二十六)整合webSocket
這個系列的文章都是工作中頻繁用到的知識,學完這個系列,應付日常開發綽綽有余。如果還想了解其他內容,掃面下方二維碼告訴我,我會進一步完善這個系列的文章!