【Springboot】Springboot整合郵件服務(HTML/附件/模板-QQ、網易)


介紹

郵件服務是常用的服務之一,作用很多,對外可以給用戶發送活動、營銷廣告等;對內可以發送系統監控報告與告警。

本文將介紹Springboot如何整合郵件服務,並給出不同郵件服務商的整合配置。

如圖所示:

 

 
Springboot整合郵件服務

開發過程

Springboot搭建

Springboot的搭建非常簡單,我們使用 Spring Initializr來構建,十分方便,選擇需要用到的模塊,就能快速完成項目的搭建:

 
Spring Initializr

 

引入依賴

為了使用郵件服務,我們需要引入相關的依賴,對於Springboot加入下面的依賴即可:

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> 

配置文件

需要配置郵件服務提供商的相關參數,如服務地址、用戶名及密碼等。下面的例子是QQ的配置,其中密碼並不是QQ密碼,而是QQ授權碼,后續我們再講怎么獲得。

Springboot的配置文件application.yml如下:

server:
  port: 8080
spring:
  profiles:
    active: qq
---
spring:
  profiles: qq
  mail:
    host: smtp.qq.com
    username: xxx@qq.com
    password: xxx
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true
---
spring:
  profiles: netEase
  mail:
    host: smtp.163.com
    username: xxx@163.com
    password: xxx
    properties:
      mail:
        smtp:
          auth: true
          starttls:
            enable: true
            required: true

實現發送服務

將JavaMailSender注入,組裝Message后,就可以發送最簡單的文本郵件了。

@Autowired private JavaMailSender emailSender; public void sendNormalText(String from, String to, String subject, String text) { SimpleMailMessage message = new SimpleMailMessage(); message.setFrom(from); message.setTo(to); message.setSubject(subject); message.setText(text); emailSender.send(message); } 

調用接口

服務調用實現后,通過Controller對外暴露REST接口,具體代碼如下:

@Value("${spring.mail.username}") private String username; @Autowired private MailService mailService; @GetMapping("/normalText") public Mono<String> sendNormalText() { mailService.sendNormalText(username, username, "Springboot Mail(Normal Text)", "This is a mail from Springboot!"); return Mono.just("sent"); } 

把實現的MailService注入到Controller里,調用對應的方法即可。本次的郵件發送人和收件人都是同一個帳戶,實際實現可以靈活配置。

通過Postman調用接口來測試一下能不能正常發送:

 
Postman


成功返回"sent",並收到了郵件,測試通過。

 

多種類型郵件

簡單文本郵件

簡單文本郵件如何發送,剛剛已經講解,不再贅述。

HTML郵件

純文本雖然已經能滿足很多需求,但很多時候也需要更加豐富的樣式來提高郵件的表現力。這時HTML類型的郵件就非常有用。

Service代碼如下:

public void sendHtml(String from, String to, String subject, String text) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); emailSender.send(message); } 

與簡單的文本不同的是,本次用到了MimeMessageMimeMessageHelper,這是非常有用的類,后續我們經常會用到,組合使用能大大豐富郵件表現形式。

Controller的代碼如下:

@GetMapping("/html") public Mono<String> sendHtml() throws MessagingException { mailService.sendHtml(username, username, "Springboot Mail(HTML)", "<h1>This is a mail from Springboot!</h1>"); return Mono.just("sent"); } 

帶附件郵件

郵件發送文件再正常不過,發送附件需要使用MimeMessageHelper.addAttachment(String attachmentFilename, InputStreamSource inputStreamSource)方法,第一個參數為附件名,第二參數為文件流資源。Service代碼如下:

public void sendAttachment(String from, String to, String subject, String text, String filePath) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addAttachment(filePath, file); emailSender.send(message); } 

Controller代碼如下:

@GetMapping("/attachment") public Mono<String> sendAttachment() throws MessagingException { mailService.sendAttachment(username, username, "Springboot Mail(Attachment)", "<h1>Please check the attachment!</h1>", "/Pictures/postman.png"); return Mono.just("sent"); } 

帶靜態資源郵件

我們訪問的網頁其實也是一個HTML,是可以帶很多靜態資源的,如圖片、視頻等。Service代碼如下:

public void sendStaticResource(String from, String to, String subject, String text, String filePath, String contentId) throws MessagingException { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(text, true); FileSystemResource file = new FileSystemResource(new File(filePath)); helper.addInline(contentId, file); emailSender.send(message); } 

其中,contentId為HTML里靜態資源的ID,需要對應好。

Controller代碼如下:

@GetMapping("/inlinePicture") public Mono<String> sendStaticResource() throws MessagingException { mailService.sendStaticResource(username, username, "Springboot Mail(Static Resource)", "<html><body>With inline picture<img src='cid:picture' /></body></html>", "/Pictures/postman.png", "picture"); return Mono.just("sent"); } 

模板郵件

Java的模板引擎很多,著名的有Freemarker、Thymeleaf、Velocity等,這不是本點的重點,所以只以Freemarker為例使用。

Service代碼如下:

@Autowired private FreeMarkerConfigurer freeMarkerConfigurer; public void sendTemplateFreemarker(String from, String to, String subject, Map<String, Object> model, String templateFile) throws Exception { MimeMessage message = emailSender.createMimeMessage(); MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateFile); String html = FreeMarkerTemplateUtils.processTemplateIntoString(template, model); helper.setText(html, true); emailSender.send(message); } 

注意需要注入FreeMarkerConfigurer,然后使用FreeMarkerTemplateUtils解析模板,返回String,就可以作為內容發送了。

Controller代碼如下:

@GetMapping("/template") public Mono<String> sendTemplateFreemarker() throws Exception { Map<String, Object> model = new HashMap<>(); model.put("username", username); model.put("templateType", "Freemarker"); mailService.sendTemplateFreemarker(username, username, "Springboot Mail(Template)", model, "template.html"); return Mono.just("sent"); } 

注意模板文件template.html要放在resources/templates/目錄下面,這樣才能找得到。

模板內容如下:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>Hello ${username}</h1> <h1>This is a mail from Springboot using ${templateType}</h1> </body> </html> 

其中${username}${templateType}為需要替換的變量名,Freemarker提供了很多豐富的變量表達式,這里不展開講了。

集成不同郵件服務商

郵件服務的提供商很多,國內最常用的應該是QQ郵箱和網易163郵箱了。

QQ

集成QQ郵件需要有必備的賬號,還要開通授權碼。開通授權碼后配置一下就可以使用了,官方的文檔如下:

什么是授權碼,它又是如何設置?

需要注意的是,開通授權碼是需要使用綁定的手機號發短信到特定號碼的,如果沒有綁定手機或者綁定手機不可用,那都會影響開通。

開通之后,授權碼就要以作為密碼配置到文件中。

163

網易的開通方式與QQ沒有太大差別,具體的指導可以看如下官方文檔:

如何開啟客戶端授權碼?

同樣也是需要綁定手機進行操作。

總結

本次例子發送后收到郵件如圖所示:

 

 
郵件

 

郵件功能強大,Springboot也非常容易整合。技術利器,善用而不濫用。


歡迎關注公眾號<南瓜慢說>,將為你持續更新...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM