Spring Boot實戰(七):Spring Boot實現仿部落格園傳送通知郵件
郵件服務已經是基礎性服務了 ,是網站的必備功能之一,當註冊了某些網站的時候,郵箱裡通常會收到一封註冊成功通知郵件或者點選啟用賬號的郵件,部落格園也是如此。本文使用Spring Boot,通過QQ郵箱來模仿部落格園傳送一封通知郵件。
部落格園傳送的“歡迎您加入部落格園”的主題郵件如圖所示。這種通知郵件,只有登入使用者名稱在變化,其它郵件內容均不變,很適合用郵件模板來處理。
模板可以實現顯示與資料分離,將模板檔案和資料通過模板引擎生成最終的HTML程式碼。
Thymeleaf是一個適用於Web和獨立環境的現代伺服器端Java模板引擎,能夠處理HTML,XML,JavaScript,CSS甚至純文字。Thymeleaf由於使用了標籤屬性做為語法,模版頁面直接用瀏覽器渲染,與其它模板引擎(比如Freemaker)相比,Thymeleaf最大的特點是能夠直接在瀏覽器中開啟並正確顯示模板頁面,而不需要啟動整個Web應用。
Thymeleaf作為Spring官方推薦的模板引擎,Spring boot對Thymeleaf支援比較友好,配置簡單,這裡使用Thymeleaf作為模板引擎。
下面正式開始實現仿部落格園傳送通知郵件。
1. pom.xml新增郵件和模板相關依賴
<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>
複製程式碼
2. application.property配置郵箱和thymelea模板
我使用的是QQ郵箱,需要獲得QQ郵箱的授權碼。
關於QQ郵箱生成授權碼:進入QQ郵箱 --> 郵箱設定 --> 賬戶 --> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服務 --> 生成授權碼 --> 手機傳送驗證簡訊 -->得到授權碼
spring.mail.host=smtp.qq.com
spring.mail.username=QQ郵箱
spring.mail.password=授權碼
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
#thymelea模板配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type:text/html
#熱部署檔案,頁面不產生快取,及時更新
spring.thymeleaf.cache=false
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
複製程式碼
3. 編寫Service及其實現
Service中有兩個方法:
sendSimpleMail用於傳送簡單的文字郵件,是一個比較基礎的案例。
sendHtmlMail用於傳送HTML郵件,傳送通知郵件用的就是這個方法。其實模板郵件也就是HTML郵件中的一個子類。
MailService:
public interface MailService {
public void sendSimpleMail(String to,String subject,String content);
public void sendHtmlMail(String to,String content);
}
複製程式碼
MailServiceImpl:
@Component
public class MailServiceImpl implements MailService {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
@Override
public void sendSimpleMail(String to,String content) {
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);//郵件接收者
message.setSubject(subject);//郵件主題
message.setText(content);//郵件內容
try {
mailSender.send(message);
logger.info("傳送簡單郵件成功!");
} catch (Exception e) {
logger.error("傳送簡單郵件時發生異常!",e);
}
}
@Override
public void sendHtmlMail(String to,String content) {
MimeMessage message = mailSender.createMimeMessage();
try {
//true表示需要建立一個multipart message
MimeMessageHelper helper = new MimeMessageHelper(message,true);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
helper.setText(content,true);
mailSender.send(message);
logger.info("傳送HTML郵件成功!");
} catch (MessagingException e) {
logger.error("傳送HTML郵件時發生異常!",e);
}
}
}
複製程式碼
4. 建立模板
在resorces/templates下建立emailTemplate.html模板,與模板配置中的spring.thymeleaf.prefix=classpath:/templates/對應,不然會找不到模板。
關於Thymeleaf的使用這裡簡單介紹一下:
引入名稱空間:。不同的約束檔案中,可能會出現不同含義的相同標記名稱,引入名稱空間可以避免混淆和衝突。
訪問資料:#{user.name}
訪問變數:${today}
輸出URL: 部落格園
更多詳情的說明和規則請參見:Thymeleaf官方檔案
emailTemplate.html:
<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8" />
<title>歡迎您加入部落格園</title>
</head>
<body>
<p>您好,您在部落格園的帳戶啟用成功,您的登入使用者名稱是:<span th:text="${username}"></span>。</p>
<p>--</p>
<div>部落格園(
<a th:href="@{https://www.cnblogs.com }">www.cnblogs.com</a>
) - 開發者的網上家園</div>
<p>程式碼改變世界!</p>
</body>
</html>
複製程式碼
5. JUnit單元測試
使用Junit進行單元測試,pom.xml中已經預設配置好了,需要編寫測試類和測試方法。測試類以xxxTest.java命名,測試方法上面加@Test註解就可以使用了。具體程式碼如下:
@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailTest {
@Autowired
private MailService mailService;
@Autowired
private TemplateEngine templateEngine;
@Test
public void testSendSimpleMail() throws Exception {
mailService.sendSimpleMail("[email protected]","測試傳送簡單文字郵件","測試傳送簡單文字郵件");
}
@Test
public void testSendTemplateMail() {
Context context = new Context();
context.setVariable("username","shangguanhao");
String emailContent = templateEngine.process("emailTemplate",context);
mailService.sendHtmlMail("[email protected]","歡迎您加入部落格園",emailContent);
}
}
複製程式碼
進行Junit測試,就可以傳送一個簡答的文字郵件和一個HTML的模板郵件,幾乎和部落格園的一模一樣(如下圖所示):
完整程式碼:GitHub地址