本篇主要介紹了Spring Boot中郵件發送,分別講解了簡單的文本郵件、HTML郵件、附件郵件、圖片郵件、模板郵件。html
在Spring Boot
項目的pom.xml
文件中引入spring-boot-starter-email
依賴java
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-email</artifactId>
<scope>email</scope>
</dependency>
複製代碼
模版郵件須要引入 spring-boot-starter-thymeleaf
插件git
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
複製代碼
163郵箱配置,注意要替換本身的帳戶信息,password爲受權碼。github
application.yml
spring
spring:
mail:
host: smtp.163.com
username: your163account@163.com
password: your163password
default-encoding: utf-8
複製代碼
QQ郵箱發送郵件配置,如下password爲受權碼數組
spring:
mail:
host: smtp.qq.com
username: yourqqaccount@qq.com
password: yourQQpassword
複製代碼
基於上節單元測試chapter5-1代碼示例基礎之上編寫bash
service目錄下建立MailService.java文件,負責業務層郵件發送功能編寫app
讓咱們利用Spring提供的JavaMailSender
接口實現郵件發送,在項目中使用到地方用@Autowired
注入郵件發送對象maven
MailService.java
spring-boot
package com.angelo.service;
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 {
@Value("${spring.mail.username}")
private String from;
@Autowired // 項目啓動時將mailSender注入
private JavaMailSender javaMailSender;
// ... 下面會一一介紹 ...
}
複製代碼
test測試目錄下建立MailServiceTest.java
測試類,對業務層代碼進行單元測試
MailServiceTest.java
package com.angelo.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.lang.reflect.Array;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MailServiceTest {
@Autowired
private MailService mailService;
@Resource
TemplateEngine templateEngine;
String to = "your163password@163.com";
// ... 下面爲一一介紹 ...
}
複製代碼
SimpleMailMessage
封裝了簡單郵件的發送、接收功能、監測異常模塊功能,這也是最簡單的一種郵件發送,建立一個郵件消息對象,設置郵件的發送者、發送對象、郵件主題、郵件內容。
MailService.java
/** * 發送文本郵件 * @param to * @param subject * @param content */
public void sendTextMail(String to, String subject, String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setTo(to); // 發送對象
message.setSubject(subject); // 郵件主題
message.setText(content); // 郵件內容
message.setFrom(from); // 郵件的發起者
javaMailSender.send(message);
}
複製代碼
對以上業務代碼進行單元測試,查看下效果
MailServiceTest.java
@Test
public void sendTextEmailTest() {
mailService.sendTextMail(to, "發送文本郵件", "hello,這是Spring Boot發送的一封文本郵件!");
}
複製代碼
基於MimeMessageHelper
建立helper
對象,設置setText第二個參數爲true,將會使用html格式打印郵件。
MailService.java
/** * 發送HTMl郵件 * @param to * @param subject * @param content * @throws MessagingException */
public void sendHtmlMail(String to, String subject, String content) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
javaMailSender.send(message);
}
複製代碼
MailServiceTest.java
@Test
public void sendHtmlEmailTest() throws MessagingException {
String content = "<html>" +
"<body>" +
"<h1 style=\"" + "color:red;" + "\">hello,這是Spring Boot發送的一封HTML郵件</h1>" +
"</body></html>";
mailService.sendHtmlMail(to, "發送HTML郵件", content);
}
複製代碼
能夠看到郵件結果使用了例子中預先設置好的郵件格式
MailService.java
/** * 發送帶附件的郵件 * @param to * @param subject * @param content * @param filePathList * @throws MessagingException */
public void sendAttachmentMail(String to, String subject, String content, String[] filePathList) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
for (String filePath: filePathList) {
System.out.println(filePath);
FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
String fileName = fileSystemResource.getFilename();
helper.addAttachment(fileName, fileSystemResource);
}
javaMailSender.send(message);
}
複製代碼
filePathList
寫上你的附件文件路徑,數組格式。
MailServiceTest.java
@Test
public void sendAttachmentEmailTest() throws MessagingException {
String[] filePathList = new String[2];
filePathList[0] = "/SpringBoot-WebApi/chapter4.zip";
filePathList[1] = "/SpringBoot-WebApi/chapter5.zip";
mailService.sendAttachmentMail(to, "發送附件郵件", "hello,這是Spring Boot發送的一封附件郵件!", filePathList);
}
複製代碼
也是基於html郵件發送,經過內嵌圖片等靜態資源,能夠直接看到圖片。
MailService.java
/** * 發送html內嵌圖片的郵件 * @param to * @param subject * @param content * @param srcPath * @param srcId * @throws MessagingException */
public void sendHtmlInlinePhotoMail(String to, String subject, String content, String srcPath, String srcId) throws MessagingException {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content, true);
FileSystemResource fileSystemResource = new FileSystemResource(new File(srcPath));
helper.addInline(srcId, fileSystemResource);
javaMailSender.send(message);
}
複製代碼
如下單元測試中srcPath爲您的本地圖片路徑,srcId要和上面業務層的helper.addInline(srcId, fileSystemResource)
srcId保持一致。
MailServiceTest.java
@Test
public void sendHtmlInlinePhotoMailTest() throws MessagingException {
String srcPath = "/SpringBoot-WebApi/chapter6/img/pic18.jpg";
String srcId = "pic18";
String content = "<html>" +
"<body>" +
"<h2>hello,這是Spring Boot發送的一封HTML內嵌圖片的郵件</h2>" +
"<img src=\'cid:"+ srcId +"\'></img>" +
"</body></html>";
mailService.sendHtmlInlinePhotoMail(to, "發送圖片郵件", content, srcPath, srcId);
}
複製代碼
郵件內容相對簡單的狀況下,咱們能夠選擇使用以上幾種簡單郵件發送方法,在複雜業務中須要用到html結構,且html裏的數據還須要動態修改,仍是選擇模版郵件,可使用
Freemarker
、thymeleaf
等模板引擎,這裏主要介紹使用thymeleaf
。
resources/templates
目錄下新建emailTemplate.html
文件
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>模板郵件</title>
</head>
<body>
您好,<span th:text="${username}"></span>,歡迎訪問個人我的博客:
<a href="https://github.com/Q-Angelo/summarize">Github</a>、
<a th:href="@{https://www.imooc.com/u/{id}(id=${id})}" href="#">慕課網</a>
</body>
</html>
複製代碼
利用上面介紹的發送html郵件便可,在單元測試文件中增長一個方法進行測試。
MailServiceTest.java
@Test
public void testTemplateEmailTest() throws MessagingException {
Context context = new Context();
context.setVariable("username", "張三");
context.setVariable("id", "2667395");
String emailContent = templateEngine.process("emailTemplate", context);
mailService.sendHtmlMail(to, "發送模板郵件", emailContent);
}
複製代碼
出現這個錯誤的緣由是網易將我發送的郵件當成了垃圾郵件,<<發送163文本郵件>>這是我填寫的郵件標題,後來發現網易是對標題裏面含了163
致使的,你們遇到相似問題多檢查下。
com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp10,DsCowADH1MxWegtcyxFjDw--.48939S2 1544256086
複製代碼
如遇到什麼問題可在下方評論區提問
做者:五月君
連接:www.imooc.com/article/267…
來源:慕課網
Github: Spring Boot實戰系列