1. 程式人生 > >47. Spring Boot傳送郵件

47. Spring Boot傳送郵件

【視訊&交流平臺】

http://study.163.com/course/introduction.htm?courseId=1004329008&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

http://study.163.com/course/introduction.htm?courseId=1004638001&utm_campaign=commission&utm_source=400000000155061&utm_medium=share

https://gitee.com/happyangellxq520/spring-boot

http://412887952-qq-com.iteye.com/blog/2321532



Spring提供了非常好用的郵件傳送。在SpringBoot的Starter模組中也為此提供了自動化配置。下面通過例項看看如何在Spring Boot中使用JavaMailSender傳送郵件。

快速入門:

那麼如何進行使用呢?很簡單最核心的就兩個步驟:

Spring Boot的工程中的pom.xml中引入spring-boot-starter-mail依賴:

<!--傳送郵件. -->

<dependency> 

   <groupId>org.springframework.boot</

groupId>

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

</dependency> 

如其他自動化配置模組一樣,在完成了依賴引入之後,只需要在application.properties中配置相應的屬性內容。

下面我們以QQ郵箱為例,在application.properties中加入如下配置(注意替換自己的使用者名稱和密碼):

########################################################

###mail setting

########################################################

#設定郵箱主機

spring.mail.host=smtp.qq.com

#設定使用者名稱

spring.mail.username=使用者名稱

#設定密碼

spring.mail.password=密碼

#設定是否需要認證,如果為true,那麼使用者名稱和密碼就必須的,

#如果設定false,可以不設定使用者名稱和密碼,當然也得看你的對接的平臺是否支援無密碼進行訪問的。

spring.mail.properties.mail.smtp.auth=true

# STARTTLS[1] 是對純文字通訊協議的擴充套件。它提供一種方式將純文字連線升級為加密連線(TLS或SSL),而不是另外使用一個埠作加密通訊。

spring.mail.properties.mail.smtp.starttls.enable=true

spring.mail.properties.mail.smtp.starttls.required=true

接下來我們通過單元測試來測試簡單郵件的傳送:

(如何在spring boot進行單元測試可以參看文章:

package com.kfit;

import org.junit.Test;

import org.junit.runner.RunWith;

importorg.springframework.beans.factory.annotation.Autowired;

importorg.springframework.boot.test.SpringApplicationConfiguration;

importorg.springframework.mail.SimpleMailMessage;

import org.springframework.mail.javamail.JavaMailSender;

importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**

 *

 *@author Angel(QQ:412887952)

 *@version v.0.1

 */

@RunWith(SpringJUnit4ClassRunner.class)

@SpringApplicationConfiguration(classes = App.class)

publicclass AppTest {

       @Autowired

       private JavaMailSendermailSender;

       /**

        *修改application.properties的使用者,才能傳送。

        */

       @Test

       publicvoidsendSimpleEmail(){

              SimpleMailMessagemessage =newSimpleMailMessage();

              message.setFrom("[email protected]");//傳送者.

              message.setTo("[email protected]");//接收者.

              message.setSubject("測試郵件(郵件主題)");//郵件主題.

              message.setText("這是郵件內容");//郵件內容.

              mailSender.send(message);//傳送郵件

       }

}

一個簡單的郵件傳送就完成了,執行一下該單元測試,看看效果如何?

由於Spring Bootstarter模組提供了自動化配置,所以在引入了spring-boot-starter-mail依賴之後,會根據配置檔案中的內容去建立JavaMailSender例項,因此我們可以直接在需要使用的地方直接@Autowired來引入郵件傳送物件。

進階使用

進階使用:

在上例中,我們通過使用SimpleMailMessage實現了簡單的郵件傳送,但是實際使用過程中,我們還可能會帶上附件、或是使用郵件模組等。這個時候我們就需要使用MimeMessage來設定複雜一些的郵件內容,下面我們就來依次實現一下。

傳送附件

傳送附件主要通過MimeMessageHelper來進行操作的,實際中也很簡單。

/**

        *測試傳送附件.(這裡傳送圖片.)

        *@throws MessagingException

        */

       @Test

       publicvoidsendAttachmentsEmail()throws MessagingException{

              //這個是javax.mail.internet.MimeMessage下的,不要搞錯了。

              MimeMessagemimeMessagemailSender.createMimeMessage();

              MimeMessageHelperhelper =newMimeMessageHelper(mimeMessage,true);

              //基本設定.

              helper.setFrom("[email protected]");//傳送者.

              helper.setTo("[email protected]");//接收者.

              helper.setSubject("測試附件(郵件主題)");//郵件主題.

              helper.setText("這是郵件內容(有附件哦.)");//郵件內容.

              //org.springframework.core.io.FileSystemResource下的:

              //附件1,獲取檔案物件.

              FileSystemResourcefile1 =newFileSystemResource(new File("D:/test/head/head1.jpg"));

              //新增附件,這裡第一個引數是在郵件中顯示的名稱,也可以直接是head.jpg,但是一定要有檔案字尾,不然就無法顯示圖片了。

              helper.addAttachment("頭像1.jpg",file1);

              //附件2

              FileSystemResourcefile2 =newFileSystemResource(new File("D:/test/head/head2.jpg"));

              helper.addAttachment("頭像2.jpg",file2);

        mailSender.send(mimeMessage);

       }

嵌入靜態資源:

除了傳送附件之外,我們在郵件內容中可能希望通過嵌入圖片等靜態資源,讓郵件獲得更好的閱讀體驗,而不是從附件中檢視具體圖片,下面的測試用例演示瞭如何通過MimeMessageHelper實現在郵件正文中嵌入靜態資源。

       內嵌圖片,給定一個CID值即可,增加附件,使用MimeMessageHelper的addAttachment即可現在一般不會做內嵌圖片,因為這樣郵件會很大,容易對伺服器造成壓力,一般做法是使用圖片連結另外,如果要做內嵌或傳送圖片,你應該使用信用較高的郵箱帳戶,否則會報錯:554 DT:SPM傳送的郵件內容包含了未被許可的資訊,或被系統識別為垃圾郵件。請檢查是否有使用者傳送病毒或者垃圾郵件
對於163郵箱伺服器會產生的其他問題,參見:http://help.163.com/09/1224/17/5RAJ4LMH00753VB8.html

以下是傳送靜態資源的核心程式碼:

/**

        *郵件中使用靜態資源.

        *@throws Exception

        */

       @Test

   publicvoid sendInlineMail()throws Exception {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = newMimeMessageHelper(mimeMessage,true);

     //基本設定.

            helper.setFrom("[email protected]");//傳送者.

            helper.setTo("[email protected]");//接收者.

            helper.setSubject("測試靜態資源(郵件主題)");//郵件主題.

            // 郵件內容,第二個引數指定傳送的是HTML格式 

            //說明:嵌入圖片<img src='cid:head'/>,其中cid:是固定的寫法,而aaa是一個contentId。

        helper.setText("<body>這是圖片:<imgsrc='cid:head' /></body>",true);

        FileSystemResource file = newFileSystemResource(new File("D:/test/head/head1.jpg"));

        helper.addInline("head",file);

        mailSender.send(mimeMessage);

    }

這裡需要注意的是addInline函式中資源名稱weixin需要與正文中cid:weixin對應起來

嵌入圖片<imgsrc='cid:head'/>,其中cid:是固定的寫法,而aaa是一個contentId。

模板郵件:

通常我們使用郵件傳送服務的時候,都會有一些固定的場景,比如重置密碼、註冊確認等,給每個使用者傳送的內容可能只有小部分是變化的。所以,很多時候我們會使用模板引擎來為各類郵件設定成模板,這樣我們只需要在傳送時去替換變化部分的引數即可。

在Spring Boot中使用模板引擎來實現模板化的郵件傳送也是非常容易的,下面我們以freemarker為例實現一下。

引入freemarker模組的依賴:

<!--引入模板引擎. -->

<dependency>

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

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

</dependency>

加入配置資訊:

########################################################

###FREEMARKER(FreeMarkerAutoConfiguration)

########################################################

spring.freemarker.allow-request-override=false

spring.freemarker.cache=true

spring.freemarker.check-template-location=true

spring.freemarker.charset=UTF-8

spring.freemarker.content-type=text/html

spring.freemarker.expose-request-attributes=false

spring.freemarker.expose-session-attributes=false

spring.freemarker.expose-spring-macro-helpers=false

#spring.freemarker.prefix=

#spring.freemarker.request-context-attribute=

#spring.freemarker.settings.*=

#spring.freemarker.suffix=.ftl

#spring.freemarker.template-loader-path=classpath:/templates/#comma-separated list

resources/templates/下,建立一個模板頁面email.ftl

<html> 

<body> 

   <h3>你好, ${username}, 這是一封模板郵件!</h3>

</body> 

</html>

最後,我們在單元測試中加入傳送模板郵件的測試用例,具體如下:

/**

        *模板郵件;

        *@throws Exception

        */

       @Test

   publicvoid sendTemplateMail()throws Exception {

        MimeMessage mimeMessage = mailSender.createMimeMessage();

        MimeMessageHelper helper = newMimeMessageHelper(mimeMessage,true);

        //基本設定.

            helper.setFrom("[email protected]");//傳送者.

            helper.setTo("[email protected]");//接收者.

            helper.setSubject("模板郵件(郵件主題)");//郵件主題.

        Map<String, Object> model = newHashMap<String, Object>();

        model.put("username", "林峰");

//      Configurationcfg=newConfiguration(Configuration.VERSION_2_3_23); 

        // 設定去哪裡讀取相應的ftl模板

        cfg.setClassForTemplateLoading(this.getClass(),"/templates"); 

        // 在模板檔案目錄中尋找名稱為name的模板檔案

        Template template   = cfg.getTemplate("email.ftl");

        String html = FreeMarkerTemplateUtils.processTemplateIntoString(template,model);

        helper.setText(html, true);

        mailSender.send(mimeMessage);

    }

另外需要在AppTest新增:

@Autowired 

 private FreeMarkerConfigurer freeMarkerConfigurer;

執行一下,就可以收到內容為你好,林峰這是一封模板郵件的郵件。這裡,我們通過傳入username的引數,在郵件內容中替換了模板中的${username}變數。

Spring Boot 系列視訊】

視訊&交流平臺:

http://study.163.com/course/introduction.htm?courseId=1004329008

http://412887952-qq-com.iteye.com/blog/2321532

網易雲課堂視訊最新更新

第十一章 Spring Boot 日誌

1、spring boot日誌—理論

2、Spring Boot日誌-logback

3、Spring Boot日誌-log4j2

第十二章 Spring Boot 知識點2

1、spring boot 服務配置和部署

2、Spring Boot 定製URL匹配規則

歷史章節

第一章 快速開始

1、Spring Boot之Hello World

2、Spring Boot之Hello World訪問404

第二章 Spring Boot之JSON

1、spring boot返回json資料

2、Spring Boot完美使用FastJson解析JSON資料

第三章 Spring Boot熱部署

1、Spring Boot熱部署(springloader)

2、springboot + devtools(熱部署)

第四章 Spring Boot資料庫

1、Spring Boot JPA/Hibernate/Spring Data概念

2、Spring Boot JPA-Hibernate

3、Spring Boot Spring Data JPA介紹

4、Spring Boot JdbcTemplate

5、Spring Boot整合MyBatis

第五章 web開發

1、全域性異常捕捉

2、配置server資訊

3、spring boot使用thymeleaf

4、Spring Boot 使用freemarker

5、Spring Boot新增JSP支援

第六章 定時任務

1、Spring Boot定時任務

2、Spring Boot 定時任務升級篇(動態修改cron引數)

3、Spring Boot 定時任務升級篇(動態新增修改刪除定時任務)

4、Spring Boot 定時任務升級篇(叢集/分散式下的定時任務說明)

5、Spring Boot Quartz介紹

6、Spring Boot Quartz在Java Project中使用

7、Spring Boot 整合Quartz普通使用

8、Spring Boot 整合Quartz升級版

9、Spring Boot 整合Quartz二次升級版

10、Spring Boot 整合Quartz-Job如何自動注入Spring容器託管的物件

第七章 Spring Boot MyBatis升級篇

1、Spring Boot MyBatis升級篇-註解

2、Spring Boot MyBatis升級篇-註解-自增ID

3、Spring Boot MyBatis升級篇-註解-增刪改查

4、Spring Boot MyBatis升級篇-註解-分頁查詢

5、Spring Boot MyBatis升級篇-註解-分頁PageHelper不生效

6、Spring Boot MyBatis升級篇-註解- mybatic insert異常:BindingException: Parameter 'name' not found

7、Spring Boot MyBatis升級篇-註解- #和$符號特別篇

8、Spring Boot MyBatis升級篇-註解[email protected]

9、Spring Boot MyBatis升級篇-註解-動態SQL(if test)-方案一:<script>

10、Spring Boot MyBatis升級篇-註解-動態SQL(if test)-方案二:@Provider

11、Spring Boot MyBatis升級篇-註解-動態SQL-引數問題

12、Spring Boot MyBatis升級篇-註解-特別篇:@MapperScan和@Mapper

13、Spring Boot MyBatis升級篇-XML

14、Spring Boot MyBatis升級篇-XML-自增ID

15、Spring Boot MyBatis升級篇-XML-增刪改查

16、Spring Boot MyBatis升級篇-XML-分頁查詢

17、Spring Boot MyBatis升級篇-XML-分頁PageHelper不生效

18、Spring Boot MyBatis升級篇-XML-動態SQL(if test)

19、Spring Boot MyBatis升級篇-XML-註解-初嘗試

20、Spring Boot MyBatis升級篇- pagehelper替換為pagehelper-spring-boot-starter

第八章 Spring Boot 知識點1

1、Spring Boot 攔截器HandlerInterceptor

2、Spring Boot啟動載入資料CommandLineRunner

3、Spring Boot環境變數讀取和屬性物件的繫結

4、Spring Boot使用自定義的properties

5、Spring Boot使用自定義的properties

6、Spring Boot使用@SpringBootApplication

7、Spring Boot 監控和管理生產環境

第十章 Spring Boot 打包部署

1、Spring Boot打包部署((提供Linux的sh檔案))

第十一章 Spring Boot 日誌

1、spring boot日誌—理論

2、Spring Boot日誌-logback

3、Spring Boot日誌-log4j2