SpringBoot(十) :郵件服務

原文出處: 純潔的微笑 html

springboot仍然在狂速發展,才五個多月沒有關注,如今看官網已經到1.5.3.RELEASE版本了。準備慢慢在寫寫springboot相關的文章,本篇文章使用springboot最新版本1.5.3進行開發。 git

發送郵件應該是網站的必備功能之一,什麼註冊驗證,忘記密碼或者是給用戶發送營銷信息。最先期的時候咱們會使用JavaMail相關api來寫發送郵件的相關代碼,後來spring推出了JavaMailSender更加簡化了郵件發送的過程,在以後springboot對此進行了封裝就有了如今的spring-boot-starter-mail,本章文章的介紹主要來自於此包。 github

簡單使用

一、pom包配置

pom包裏面添加spring-boot-starter-mail包引用 spring

 

<dependencies> api

<dependency> springboot

<groupId>org.springframework.boot</groupId> 服務器

<artifactId>spring-boot-starter-mail</artifactId> 網絡

</dependency> 併發

</dependencies> app

二、在application.properties中添加郵箱配置

 

spring.mail.host=smtp.qiye.163.com //郵箱服務器地址

spring.mail.username=xxx@oo.com //用戶名

spring.mail.password=xxyyooo    //密碼

spring.mail.default-encoding=UTF-8

mail.fromMail.addr=xxx@oo.com  //以誰來發送郵件

三、編寫mailService,這裏只提出實現類。

 

@Component

public class MailServiceImpl implements MailService{

private final Logger logger = LoggerFactory.getLogger(this.getClass());

@Autowired

private JavaMailSender mailSender;

@Value("${mail.fromMail.addr}")

private String from;

@Override

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);

try {

mailSender.send(message);

logger.info("簡單郵件已經發送。");

} catch (Exception e) {

logger.error("發送簡單郵件時發生異常!", e);

}

}

}

四、編寫test類進行測試

 

@RunWith(SpringRunner.class)

@SpringBootTest

public class MailServiceTest {

@Autowired

private MailService MailService;

@Test

public void testSimpleMail() throws Exception {

MailService.sendSimpleMail("ityouknow@126.com","test simple mail"," hello this is simple mail");

}

}

至此一個簡單的文本發送就完成了。

加點料

可是在正常使用的過程當中,咱們一般在郵件中加入圖片或者附件來豐富郵件的內容,下面講介紹如何使用springboot來發送豐富的郵件。

發送html格式郵件

其它都不變在MailService添加sendHtmlMail方法.

 

public void sendHtmlMail(String to, String subject, 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);

}

}

在測試類中構建html內容,測試發送

 

@Test

public void testHtmlMail() throws Exception {

String content="<html>\n" +

"<body>\n" +

"    <h3>hello world ! 這是一封Html郵件!</h3>\n" +

"</body>\n" +

"</html>";

MailService.sendHtmlMail("ityouknow@126.com","test simple mail",content);

}

發送帶附件的郵件

在MailService添加sendAttachmentsMail方法.

 

public void sendAttachmentsMail(String to, String subject, String content, String filePath){

MimeMessage message = mailSender.createMimeMessage();

try {

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);

helper.setTo(to);

helper.setSubject(subject);

helper.setText(content, true);

FileSystemResource file = new FileSystemResource(new File(filePath));

String fileName = filePath.substring(filePath.lastIndexOf(File.separator));

helper.addAttachment(fileName, file);

mailSender.send(message);

logger.info("帶附件的郵件已經發送。");

} catch (MessagingException e) {

logger.error("發送帶附件的郵件時發生異常!", e);

}

}

添加多個附件可使用多條 helper.addAttachment(fileName, file)

在測試類中添加測試方法

 

@Test

public void sendAttachmentsMail() {

String filePath="e:\\tmp\\application.log";

mailService.sendAttachmentsMail("ityouknow@126.com", "主題:帶附件的郵件", "有附件,請查收!", filePath);

}

發送帶靜態資源的郵件

郵件中的靜態資源通常就是指圖片,在MailService添加sendAttachmentsMail方法.

 

public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){

MimeMessage message = mailSender.createMimeMessage();

try {

MimeMessageHelper helper = new MimeMessageHelper(message, true);

helper.setFrom(from);

helper.setTo(to);

helper.setSubject(subject);

helper.setText(content, true);

FileSystemResource res = new FileSystemResource(new File(rscPath));

helper.addInline(rscId, res);

mailSender.send(message);

logger.info("嵌入靜態資源的郵件已經發送。");

} catch (MessagingException e) {

logger.error("發送嵌入靜態資源的郵件時發生異常!", e);

}

}

在測試類中添加測試方法

 

@Test

public void sendInlineResourceMail() {

String rscId = "neo006";

String content="<html><body>這是有圖片的郵件:<img src=\'cid:" + rscId + "\' ></body></html>";

String imgPath = "C:\\Users\\summer\\Pictures\\favicon.png";

mailService.sendInlineResourceMail("ityouknow@126.com", "主題:這是有圖片的郵件", content, imgPath, rscId);

}

添加多個圖片可使用多條 <img src=’cid:」 + rscId + 「‘ > 和 helper.addInline(rscId, res) 來實現
到此全部的郵件發送服務已經完成了。

郵件系統

上面發送郵件的基礎服務就這些了,可是若是咱們要作成一個郵件系統的話還須要考慮如下幾個問題:

郵件模板

咱們會常常收到這樣的郵件:

 

尊敬的neo用戶:

恭喜您註冊成爲xxx網的用戶,,同時感謝您對xxx的關注與支持並歡迎您使用xx的產品與服務。

...

其中只有neo這個用戶名在變化,其它郵件內容均不變,若是每次發送郵件都須要手動拼接的話會不夠優雅,而且每次模板的修改都須要改動代碼的話也很不方便,所以對於這類郵件需求,都建議作成郵件模板來處理。模板的本質很簡單,就是在模板中替換變化的參數,轉換爲html字符串便可,這裏以thymeleaf爲例來演示。

一、pom中導入thymeleaf的包

 

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-thymeleaf</artifactId>

</dependency>

二、在resorces/templates下建立emailTemplate.html

 

<!DOCTYPE html>

<html lang="zh" xmlns:th="http://www.thymeleaf.org">

<head>

<meta charset="UTF-8"/>

<title>Title</title>

</head>

<body>

您好,這是驗證郵件,請點擊下面的連接完成驗證,

<a href="#" th:href="@{ http://www.ityouknow.com/neo/{id}(id=${id}) }">激活帳號</a>

</body>

</html>

三、解析模板併發送

 

@Test

public void sendTemplateMail() {

//建立郵件正文

Context context = new Context();

context.setVariable("id", "006");

String emailContent = templateEngine.process("emailTemplate", context);

mailService.sendHtmlMail("ityouknow@126.com","主題:這是模板郵件",emailContent);

}

發送失敗

由於各類緣由,總會有郵件發送失敗的狀況,好比:郵件發送過於頻繁、網絡異常等。在出現這種狀況的時候,咱們通常會考慮從新重試發送郵件,會分爲如下幾個步驟來實現:

一、接收到發送郵件請求,首先記錄請求而且入庫。
二、調用郵件發送接口發送郵件,而且將發送結果記錄入庫。
三、啓動定時系統掃描時間段內,未發送成功而且重試次數小於3次的郵件,進行再次發送

異步發送

不少時候郵件發送並非咱們主業務必須關注的結果,好比通知類、提醒類的業務能夠容許延時或者失敗。這個時候能夠採用異步的方式來發送郵件,加快主交易執行速度,在實際項目中能夠採用MQ發送郵件相關參數,監聽到消息隊列以後啓動發送郵件。

能夠參考前期文章:springboot(八):RabbitMQ詳解 來實現。

示例代碼

參考

spring boot 發送郵件

相關文章
相關標籤/搜索