SpringBoot實(shí)現(xiàn)郵件發(fā)送功能的詳細(xì)步驟(普通郵件、HTML郵件、附件郵件)
郵件發(fā)送是后端系統(tǒng)的常見(jiàn)功能——注冊(cè)驗(yàn)證碼、系統(tǒng)告警、周報(bào)推送。SpringBoot 封裝了 JavaMail,配置簡(jiǎn)單,API 友好。
一、配置
1. 引入依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>2. 郵箱配置
spring:
mail:
host: smtp.qq.com
port: 465
username: your_email@qq.com
password: 你的授權(quán)碼 # 不是QQ密碼,是SMTP授權(quán)碼
properties:
mail:
smtp:
auth: true
ssl:
enable: true
socketFactory:
port: 465
class: javax.net.ssl.SSLSocketFactory授權(quán)碼獲取:QQ郵箱 → 設(shè)置 → 賬號(hào) → 開(kāi)啟SMTP服務(wù) → 生成授權(quán)碼
二、發(fā)送郵件
1. 簡(jiǎn)單文本郵件
@Service
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
}
2. HTML 郵件
public void sendHtmlMail(String to, String subject, String htmlContent)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // true = HTML 格式
mailSender.send(message);
}
HTML 內(nèi)容示例:
String html = "<div style='padding:20px;max-width:600px;margin:0 auto'>"
+ "<h2 style='color:#e74c3c'>秒殺成功通知</h2>"
+ "<p>親愛(ài)的用戶:</p>"
+ "<p>您在秒殺活動(dòng)中搶購(gòu)的商品已成功下單!</p>"
+ "<table border='1' cellpadding='8' style='border-collapse:collapse'>"
+ "<tr><td>訂單號(hào)</td><td>" + orderNo + "</td></tr>"
+ "<tr><td>商品名稱</td><td>iPhone 15</td></tr>"
+ "<tr><td>金額</td><td>¥4999</td></tr>"
+ "</table>
<p>祝您購(gòu)物愉快!</p></div>";3. 帶附件郵件
public void sendAttachmentMail(String to, String subject,
String content, String filePath)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content);
// 添加附件
File file = new File(filePath);
helper.addAttachment(file.getName(), file);
mailSender.send(message);
}
4. 帶內(nèi)聯(lián)圖片
public void sendInlineImageMail(String to, String subject,
String content, String imgPath)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(
"<html><body><img src='cid:image1'/><p>" + content + "</p></body></html>",
true
);
FileSystemResource img = new FileSystemResource(new File(imgPath));
helper.addInline("image1", img);
mailSender.send(message);
}
三、模板郵件
1. 使用 Thymeleaf 模板
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency><!-- resources/templates/mail/welcome.html -->
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h2 th:text="'歡迎 ' + ${username} + ' 加入!'">歡迎加入</h2>
<p>請(qǐng)點(diǎn)擊以下鏈接激活賬戶:</p>
<a th:href="${activateUrl}" rel="external nofollow" >激活賬戶</a>
<p th:text="'鏈接有效期:' + ${expireHours} + ' 小時(shí)'">有效期</p>
</body>
</html>@Service
public class TemplateMailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
@Value("${spring.mail.username}")
private String from;
public void sendTemplateMail(String to, String subject,
Map<String, Object> params)
throws MessagingException {
// 渲染模板
Context context = new Context();
context.setVariables(params);
String html = templateEngine.process("mail/welcome.html", context);
// 發(fā)送
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(html, true);
mailSender.send(message);
}
}
四、批量發(fā)送
public void sendBatch(List<String> toList, String subject,
String content) {
for (String to : toList) {
try {
sendSimpleMail(to, subject, content);
// 每封間隔 3 秒,避免被判定為垃圾郵件
Thread.sleep(3000);
} catch (Exception e) {
log.error("發(fā)送失敗: {}", to, e);
}
}
}
五、異步發(fā)送
@Service
public class AsyncMailService {
@Async("taskExecutor")
public void sendMailAsync(String to, String subject, String content) {
mailService.sendSimpleMail(to, subject, content);
log.info("郵件已異步發(fā)送: {}", to);
}
}
六、常見(jiàn)問(wèn)題
1. 535 Error:登錄失敗
# 原因:用了QQ密碼而不是授權(quán)碼
# 解決:去QQ郵箱 → 設(shè)置 → 賬號(hào) → 生成授權(quán)碼
spring:
mail:
password: 你的授權(quán)碼 # 不是QQ密碼2. 554 被判定為垃圾郵件
// 原因:郵件內(nèi)容太短或太模板化 // 解決: // - 內(nèi)容不要太雷同 // - 加收件人姓名個(gè)性化 // - 控制發(fā)送頻率(每分鐘不超過(guò) 10 封)
3. 發(fā)送超時(shí)
spring:
mail:
properties:
mail:
smtp:
connectiontimeout: 5000
timeout: 5000
writetimeout: 5000七、秒殺系統(tǒng)應(yīng)用
@Service
public class SeckillMailService {
@Async("taskExecutor")
public void notifySeckillResult(Long userId, String productName,
boolean success, String orderNo) {
Map<String, Object> params = new HashMap<>();
params.put("userId", userId);
params.put("productName", productName);
params.put("success", success);
params.put("orderNo", orderNo);
templateMailService.sendTemplateMail(
"user@example.com",
"秒殺結(jié)果通知",
params
);
}
}
總結(jié)
發(fā)送方式: 簡(jiǎn)單文本 → SimpleMailMessage HTML內(nèi)容 → MimeMessageHelper(true) 帶附件 → helper.addAttachment() 內(nèi)聯(lián)圖片 → helper.addInline() 注意事項(xiàng): 使用授權(quán)碼而非密碼 控制發(fā)送頻率 異步發(fā)送不影響主流程
到此這篇關(guān)于SpringBoot實(shí)現(xiàn)郵件發(fā)送功能的詳細(xì)步驟(普通郵件、HTML郵件、附件郵件)的文章就介紹到這了,更多相關(guān)SpringBoot郵件發(fā)送功能內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot集成Redis,并自定義對(duì)象序列化操作
這篇文章主要介紹了SpringBoot集成Redis,并自定義對(duì)象序列化操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
FilenameUtils.getName?函數(shù)源碼分析
這篇文章主要為大家介紹了FilenameUtils.getName?函數(shù)源碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
IntelliJ IDEA2020.1版本更新pom文件自動(dòng)導(dǎo)包的方法
這篇文章主要介紹了IntelliJ IDEA2020.1版本更新pom文件自動(dòng)導(dǎo)包的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
MyBatis 源碼分析 之SqlSession接口和Executor類
mybatis框架在操作數(shù)據(jù)的時(shí)候,離不開(kāi)SqlSession接口實(shí)例類的作用,下面通過(guò)本文給大家實(shí)例剖析MyBatis 源碼分析之SqlSession接口和Executor類,需要的朋友參考下吧2017-02-02
MyBatis傳入多個(gè)參數(shù)時(shí)parameterType的寫法
這篇文章主要介紹了MyBatis傳入多個(gè)參數(shù)時(shí)parameterType的寫法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-12-12
Spring連接Mysql數(shù)據(jù)庫(kù)全過(guò)程
這篇文章主要介紹了Spring連接Mysql數(shù)據(jù)庫(kù)全過(guò)程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Java程序開(kāi)發(fā)中abstract 和 interface的區(qū)別詳解
abstract class和interface在Java語(yǔ)言中都是用來(lái)進(jìn)行抽象類。但是兩者有什么區(qū)別呢,接下來(lái)小編給大家?guī)?lái)了abstract 和 interface的區(qū)別詳解,感興趣的朋友一起學(xué)習(xí)吧2016-06-06
java代碼獲取數(shù)據(jù)庫(kù)表里數(shù)據(jù)的總數(shù)操作
這篇文章主要介紹了java代碼獲取數(shù)據(jù)庫(kù)表里數(shù)據(jù)的總數(shù)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08

