SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法
引言
下面將詳細介紹SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法,包括普通文本郵件、HTML郵件、帶附件郵件以及使用模板的郵件發(fā)送。
一、環(huán)境準(zhǔn)備
1. 添加Maven依賴
在pom.xml文件中添加郵件發(fā)送相關(guān)依賴:
<!-- 郵件發(fā)送核心依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 可選:如果需要使用FreeMarker模板 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2. 配置郵件服務(wù)器
在application.yml中配置SMTP服務(wù)器信息:
spring:
mail:
host: smtp.qq.com # SMTP服務(wù)器地址
port: 587 # 端口號(QQ郵箱用587,SSL用465)
username: your-email@qq.com # 發(fā)件人郵箱
password: your-auth-code # 授權(quán)碼(非郵箱密碼)
default-encoding: UTF-8
protocol: smtp
properties:
mail:
smtp:
auth: true
starttls:
enable: true
required: true
ssl:
enable: false # 如果使用465端口則設(shè)為true
debug: true # 開發(fā)階段可開啟調(diào)試模式
注意:需要先在郵箱中開啟SMTP服務(wù)并獲取授權(quán)碼:
- QQ郵箱:設(shè)置 > 賬戶 > POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務(wù) > 開啟POP3/SMTP服務(wù)
- 163郵箱:設(shè)置 > POP3/SMTP/IMAP > 開啟SMTP服務(wù)
- 企業(yè)郵箱:根據(jù)不同服務(wù)商的指引開啟
二、郵件實體類
創(chuàng)建郵件信息的實體類:
import lombok.Data;
import java.io.Serializable;
@Data
public class MailDTO implements Serializable {
private String recipient; // 收件人郵箱
private String[] recipients; // 多個收件人(可選)
private String subject; // 郵件主題
private String content; // 郵件內(nèi)容
private String templateName; // 模板名稱(可選)
private Object templateModel; // 模板數(shù)據(jù)模型(可選)
}
三、郵件發(fā)送工具類
創(chuàng)建一個通用的郵件發(fā)送工具類:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;
@Component
@Slf4j
public class MailService {
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String fromEmail;
@Autowired(required = false)
private FreeMarkerConfigurer freeMarkerConfigurer;
/**
* 發(fā)送簡單文本郵件
*/
public void sendSimpleMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromEmail);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
try {
mailSender.send(message);
log.info("簡單郵件發(fā)送成功,收件人:{}", to);
} catch (Exception e) {
log.error("簡單郵件發(fā)送失敗", e);
throw new RuntimeException("郵件發(fā)送失敗", e);
}
}
/**
* 發(fā)送HTML格式郵件
*/
public void sendHtmlMail(String to, String subject, String htmlContent) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(fromEmail);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(htmlContent, true); // true表示是HTML內(nèi)容
mailSender.send(message);
log.info("HTML郵件發(fā)送成功,收件人:{}", to);
} catch (MessagingException e) {
log.error("HTML郵件發(fā)送失敗", e);
throw new RuntimeException("HTML郵件發(fā)送失敗", e);
}
}
/**
* 發(fā)送帶附件的郵件
*/
public void sendAttachmentMail(String to, String subject, String content, String filePath) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(fromEmail);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, false); // false表示純文本
// 添加附件
FileSystemResource file = new FileSystemResource(new File(filePath));
String fileName = file.getFilename();
helper.addAttachment(fileName, file);
mailSender.send(message);
log.info("帶附件郵件發(fā)送成功,收件人:{}", to);
} catch (MessagingException e) {
log.error("帶附件郵件發(fā)送失敗", e);
throw new RuntimeException("帶附件郵件發(fā)送失敗", e);
}
}
/**
* 發(fā)送帶內(nèi)聯(lián)圖片的郵件
*/
public void sendInlineResourceMail(String to, String subject, String content, String filePath, String contentId) {
MimeMessage message = mailSender.createMimeMessage();
try {
MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
helper.setFrom(fromEmail);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true); // HTML內(nèi)容
// 添加內(nèi)聯(lián)圖片
FileSystemResource resource = new FileSystemResource(new File(filePath));
helper.addInline(contentId, resource);
mailSender.send(message);
log.info("帶內(nèi)聯(lián)圖片郵件發(fā)送成功,收件人:{}", to);
} catch (MessagingException e) {
log.error("帶內(nèi)聯(lián)圖片郵件發(fā)送失敗", e);
throw new RuntimeException("帶內(nèi)聯(lián)圖片郵件發(fā)送失敗", e);
}
}
/**
* 發(fā)送模板郵件
*/
public void sendTemplateMail(String to, String subject, String templateName, Map<String, Object> model) {
try {
// 使用FreeMarker模板
String htmlContent = FreeMarkerTemplateUtils.processTemplateIntoString(
freeMarkerConfigurer.getConfiguration().getTemplate(templateName),
model);
// 發(fā)送HTML郵件
sendHtmlMail(to, subject, htmlContent);
} catch (Exception e) {
log.error("模板郵件發(fā)送失敗", e);
throw new RuntimeException("模板郵件發(fā)送失敗", e);
}
}
}
四、創(chuàng)建郵件模板
如果需要使用FreeMarker模板,在src/main/resources/templates/目錄下創(chuàng)建郵件模板:
1. 注冊確認(rèn)模板(register.html)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注冊確認(rèn)</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; }
.container { max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0; }
.header { background-color: #4CAF50; color: white; padding: 10px; text-align: center; }
.content { padding: 20px; }
.button { display: inline-block; padding: 10px 20px; background-color: #4CAF50; color: white; text-decoration: none; }
.footer { margin-top: 20px; font-size: 12px; color: #666; }
</style>
</head>
<body>
<div class="container">
<div class="header">
<h2>注冊確認(rèn)郵件</h2>
</div>
<div class="content">
<p>親愛的 ${username}:</p>
<p>歡迎注冊我們的系統(tǒng)!請點擊下方按鈕完成郵箱驗證:</p>
<p>
<a href="${verifyUrl}" rel="external nofollow" class="button">點擊驗證郵箱</a>
</p>
<p>如果您沒有注冊我們的系統(tǒng),請忽略此郵件。</p>
</div>
<div class="footer">
<p>此郵件由系統(tǒng)自動發(fā)送,請勿回復(fù)。</p>
</div>
</div>
</body>
</html>
五、Controller層實現(xiàn)
創(chuàng)建REST接口用于測試郵件發(fā)送:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api/mail")
public class MailController {
@Autowired
private MailService mailService;
/**
* 發(fā)送簡單文本郵件
*/
@PostMapping("/simple")
public String sendSimpleMail(
@RequestParam String to,
@RequestParam String subject,
@RequestParam String content) {
mailService.sendSimpleMail(to, subject, content);
return "簡單郵件發(fā)送成功";
}
/**
* 發(fā)送HTML郵件
*/
@PostMapping("/html")
public String sendHtmlMail(
@RequestParam String to,
@RequestParam String subject,
@RequestParam String htmlContent) {
mailService.sendHtmlMail(to, subject, htmlContent);
return "HTML郵件發(fā)送成功";
}
/**
* 發(fā)送帶附件的郵件
*/
@PostMapping("/attachment")
public String sendAttachmentMail(
@RequestParam String to,
@RequestParam String subject,
@RequestParam String content,
@RequestParam String filePath) {
mailService.sendAttachmentMail(to, subject, content, filePath);
return "帶附件郵件發(fā)送成功";
}
/**
* 發(fā)送注冊確認(rèn)郵件(使用模板)
*/
@PostMapping("/register")
public String sendRegisterMail(
@RequestParam String to,
@RequestParam String username,
@RequestParam String verifyCode) {
Map<String, Object> model = new HashMap<>();
model.put("username", username);
model.put("verifyUrl", "http://yourdomain.com/verify?code=" + verifyCode);
mailService.sendTemplateMail(to, "【系統(tǒng)】注冊確認(rèn)郵件", "register.html", model);
return "注冊確認(rèn)郵件發(fā)送成功";
}
/**
* 發(fā)送帶內(nèi)聯(lián)圖片的郵件
*/
@PostMapping("/inline")
public String sendInlineMail(
@RequestParam String to,
@RequestParam String subject,
@RequestParam String imagePath) {
// HTML內(nèi)容中引用內(nèi)聯(lián)圖片
String htmlContent = "<html><body><h3>這是一封帶內(nèi)聯(lián)圖片的郵件</h3>" +
"<img src='cid:image1'></body></html>";
mailService.sendInlineResourceMail(to, subject, htmlContent, imagePath, "image1");
return "帶內(nèi)聯(lián)圖片郵件發(fā)送成功";
}
}
六、SpringBoot主程序
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MailApplication {
public static void main(String[] args) {
SpringApplication.run(MailApplication.class, args);
}
}
七、常見郵件服務(wù)器配置
1. QQ郵箱配置
spring:
mail:
host: smtp.qq.com
port: 587
username: your-qq@qq.com
password: 你的授權(quán)碼
properties:
mail:
smtp:
auth: true
starttls:
enable: true
2. 163郵箱配置
spring:
mail:
host: smtp.163.com
port: 465
username: your-email@163.com
password: 你的授權(quán)碼
properties:
mail:
smtp:
auth: true
ssl:
enable: true
3. Gmail配置
spring:
mail:
host: smtp.gmail.com
port: 587
username: your-email@gmail.com
password: 你的授權(quán)碼(或應(yīng)用密碼)
properties:
mail:
smtp:
auth: true
starttls:
enable: true
八、安全性建議
授權(quán)碼管理:
- 不要在配置文件中硬編碼真實的授權(quán)碼
- 建議使用環(huán)境變量或配置中心管理敏感信息
- 生產(chǎn)環(huán)境使用
application-prod.yml并從Git中排除
郵件頻率控制:
- 實現(xiàn)發(fā)送頻率限制,避免被郵件服務(wù)器標(biāo)記為垃圾郵件
- 考慮使用線程池異步發(fā)送郵件,提高性能
監(jiān)控與日志:
- 記錄所有郵件發(fā)送日志,便于排查問題
- 實現(xiàn)郵件發(fā)送失敗重試機制
九、測試示例
發(fā)送簡單文本郵件:
POST /api/mail/simple?to=recipient@example.com&subject=測試郵件&content=這是一封測試郵件
發(fā)送注冊確認(rèn)郵件:
POST /api/mail/register?to=user@example.com&username=張三&verifyCode=123456
發(fā)送帶附件的郵件:
POST /api/mail/attachment?to=user@example.com&subject=帶附件郵件&content=請查看附件&filePath=/path/to/file.pdf
通過以上配置和代碼,您可以在SpringBoot項目中輕松實現(xiàn)各種類型的郵件發(fā)送功能,滿足用戶注冊驗證、通知提醒、報表發(fā)送等業(yè)務(wù)需求。
以上就是SpringBoot整合Email發(fā)送的完整配置和實現(xiàn)方法的詳細內(nèi)容,更多關(guān)于SpringBoot整合Email發(fā)送的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
解決SpringMvc后臺接收json數(shù)據(jù)中文亂碼問題的幾種方法
本篇文章主要介紹了解決SpringMvc后臺接收json數(shù)據(jù)中文亂碼問題的幾種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01
Spring?Cloud?Alibaba負載均衡實現(xiàn)方式
這篇文章主要為大家介紹了Spring?Cloud?Alibaba負載均衡實現(xiàn)方式詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10
Java Quartz觸發(fā)器CronTriggerBean配置用法詳解

