SpringBoot發送郵件
課程目錄
1、第一部分 背景
- 使用場景
- 發送原理
- 發送曆史
- SpringBoot介紹
- 前置知識
2、第二部分 實踐
- 文本郵件
- HTML郵件
- 附件郵件
- 圖檔郵件
- 郵件模闆
- 郵件系統
第一部分 背景
1、郵件使用場景
- 注冊驗證
- 網站營銷
- 安全防線
- 提醒監控
- 觸發機制
2、郵件發送原理
- SMPTP協定 發送協定
- POP3協定 接收協定
- IMAP協定 對POP3補充
- Mime協定
3、郵件發送曆史
- 1969年10月世界第一封
- 1987年9月14日中國第一封
4、SpringBoot介紹
- 約定大于配置
- 簡單快速開發
- 強大生态鍊
5、前置知識
- Spring
- Maven
- HTML
- Thymeleaf
第二部分 實踐
1、學習路徑
- 基礎配置
- 異常處理
- 2、環境配置
初始化SpringBoot項目
https://start.spring.io/版本:2.3.5.RELEASE
Service示例
package com.example.demo.service;
import org.springframework.stereotype.Service;
@Service
public class HelloService {
public void sayHello(){
System.out.println("Hello");
}
}
測試類
package com.example.demo;
import com.example.demo.service.HelloService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoApplicationTests {
@Autowired
HelloService helloService;
@Test
void sayHelloTest() {
helloService.sayHello();
}
}
3、項目配置
- 引入jar包
<!-- 郵件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!-- 模闆引擎 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 配置郵箱參數
spring.mail.host=smtp.163.com
[email protected]
# 戶端授權碼
spring.mail.password=password
spring.mail.default-encoding=UTF-8
4、發送郵件
- 封裝SimpleMailMessage
- JavaMailSender進行發送
package com.example.demo.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Service;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
@Service
public class MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Value("${spring.mail.username}")
private String fromUser;
@Autowired
private JavaMailSender mailSender;
/**
* 文本郵件
*
* @param toUser
* @param subject
* @param content
*/
public void sendSimpleMail(
String toUser, String subject,
String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(fromUser);
message.setTo(toUser);
message.setSubject(subject);
message.setText(content);
mailSender.send(message);
}
/**
* html郵件
*
* @param toUser
* @param subject
* @param content
*/
public void sendHtmlMail(
String toUser, String subject,
String content) {
logger.info("html郵件開始:{} {} {}", toUser, subject, content);
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = null;
try {
helper = new MimeMessageHelper(message, true);
helper.setFrom(fromUser);
helper.setTo(toUser);
helper.setSubject(subject);
helper.setText(content, true);
mailSender.send(message);
logger.info("html郵件成功");
} catch (MessagingException e) {
e.printStackTrace();
logger.error("html郵件失敗:", e);
}
}
/**
* 附件郵件
*
* @param toUser
* @param subject
* @param content
* @param filePath 絕對路徑
* @throws MessagingException
*/
public void sendAttachmentsMail(
String toUser, String subject,
String content, String filePath)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromUser);
helper.setTo(toUser);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource file = new FileSystemResource(new File(filePath));
// 可以多次添加附件
helper.addAttachment(file.getFilename(), file);
mailSender.send(message);
}
/**
* 圖檔郵件
*
* @param toUser
* @param subject
* @param content
* @param resourcePath
* @param resourceId
* @throws MessagingException
*/
public void sendInlineResourceMail(
String toUser, String subject,
String content, String resourcePath, String resourceId)
throws MessagingException {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(fromUser);
helper.setTo(toUser);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource resource = new FileSystemResource(new File(resourcePath));
// 可以多次添加圖檔
helper.addInline(resourceId, resource);
mailSender.send(message);
}
}
- 發送測試
package com.example.demo;
import com.example.demo.service.MailService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.mail.MessagingException;
import java.io.IOException;
@SpringBootTest
class DemoApplicationTests {
@Autowired
MailService mailService;
@Autowired
TemplateEngine templateEngine;
@Test
void sendSimpleMailTest() {
mailService.sendSimpleMail(
"[email protected]",
"文本郵件标題",
"郵件内容"
);
}
@Test
void sendHtmlMailTest() {
String content = "<html>" +
"<body>" +
"<h3>這是郵件内容</h3>" +
"</body>" +
"</html>";
mailService.sendHtmlMail(
"[email protected]",
"HTML郵件标題",
content
);
}
@Test
void sendAttachmentsMailTest() throws MessagingException, IOException {
String filePath = "name.txt";
ClassPathResource resource = new ClassPathResource(filePath);
mailService.sendAttachmentsMail(
"[email protected]",
"附件郵件标題",
"郵件内容",
resource.getFile().getAbsolutePath()
);
}
@Test
void sendInlineResourceMailTest() throws IOException, MessagingException {
String imagePath = "demo.jpg";
String resourceId = "image001";
String content = "<html>" +
"<body>" +
"<h3>這是郵件内容</h3>" +
"<img src='cid:" + resourceId + "'>" +
"</body>" +
"</html>";
ClassPathResource resource = new ClassPathResource(imagePath);
mailService.sendInlineResourceMail(
"[email protected]",
"圖檔郵件标題",
content,
resource.getFile().getAbsolutePath(),
resourceId
);
}
@Test
void sendTemplateMailTest() {
Context content = new Context();
content.setVariable("id", "007");
String mailContent = templateEngine.process("mail", content);
mailService.sendHtmlMail(
"[email protected]",
"模闆郵件标題",
mailContent
);
}
}
模闆
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8"/>
<title>Title</title>
</head>
<body>
<p>感謝注冊</p>
<p><a href="" th:href="@{https://www.baidu.com/{id}(id=${id})}">點選激活</a></p>
</body>
</html>
常見錯誤
- 421 HL:ICC 該IP同僚并發連接配接數過大
-
451 Requested mail action not taken: too much fail
登入失敗次數過多,被臨時禁止登入
- 553 authentication is required 認證失敗
- 更多錯誤
- 獨立微服務MQ
- 定時重試郵件
- 異步發送
總結
- 郵件發送曆史和原理
- SpringBoot 和郵件系統
- 各種類型郵件的發送