当前位置: 首页>开发笔记>正文

玩轉 SpringBoot 2 之發送郵件篇

玩轉 SpringBoot 2 之發送郵件篇

前言

通過本文你將了解到SpringBoot 2 中發送郵件使用教程,具體詳細內容如下:

  • 發送普通的郵件
  • 發送html格式郵件
  • 發送html 中帶圖片的郵件
  • 發送帶附件的郵件

閱讀前需要你必須了解如何搭建 SpringBoot 項目,

簡單介紹

Spring 提供了JavaMailSender 接口幫我們來實現郵件的發送。在SpringBoot 更是提供了郵件的發送的 starter 依賴來簡化郵件發送代碼的開發 。

實戰操作演示

郵件功能開發前準備

第一步:先引入mail 的 starter依賴在pom.xm中,具體代碼如下:

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

第二步:添加的配置信息 我們這里是通過yml 方式進行配置

spring:mail:host: smtp.126.comusername: 郵箱用戶名password: 郵箱密碼properties:mail:smtp:auth: true  # 需要驗證登錄名和密碼starttls:enable: true  # 需要TLS認證 保證發送郵件安全驗證required: true

發送普通的郵件

開發步驟:

第一步:通過 SimpleMailMessage 設置發送郵件信息,具體信息如下:

  • 發送人(From)
  • 被發送人(To)
  • 主題(Subject)
  • 內容(Text)

第二步:通過JavaMailSender send(SimpleMailMessage simpleMailMessage) 方法發送郵件。

具體代碼如下:

package cn.lijunkui.mail;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;@Service
public class MailService {private final Logger logger = LoggerFactory.getLogger(this.getClass());@Autowiredprivate JavaMailSender sender;@Value("${spring.mail.username}")private String formMail;public void sendSimpleMail(String toMail,String subject,String content) {SimpleMailMessage simpleMailMessage = new SimpleMailMessage();simpleMailMessage.setFrom(formMail);simpleMailMessage.setTo(toMail);simpleMailMessage.setSubject(subject);simpleMailMessage.setText(content);try {sender.send(simpleMailMessage);logger.info("發送給"+toMail+"簡單郵件已經發送。 subject:"+subject);}catch (Exception e){logger.info("發送給"+toMail+"send mail error subject:"+subject);e.printStackTrace();}}
}

發送 html 格式郵件

開發步驟:

第一步:通過JavaMailSender 的 createMimeMessage() 創建 MimeMessage 對象實例
第二步:將 MimeMessage 放入到MimeMessageHelper 構造函數中,并通過MimeMessageHelper 設置發送郵件信息。(發送人, 被發送人,主題,內容)
第三步:通過JavaMailSender send(MimeMessage mimeMessage)發送郵件。

具體代碼如下:

public void sendHtmlMail(String toMail,String subject,String content) {MimeMessage mimeMessage = sender.createMimeMessage();try {MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);mimeMessageHelper.setTo(toMail);mimeMessageHelper.setFrom(formMail);mimeMessageHelper.setText(content,true);mimeMessageHelper.setSubject(subject);sender.send(mimeMessage);logger.info("發送給"+toMail+"html郵件已經發送。 subject:"+subject);} catch (MessagingException e) {logger.info("發送給"+toMail+"html send mail error subject:"+subject);e.printStackTrace();}}

發送 html 中帶圖片的郵件

發送 html 中帶圖片的郵件和發送 html郵件操作基本一致,不同的是需要額外在通過MimeMessageHelper addInline 的方法去設置圖片信息。

開發步驟:

  1. 定義html 嵌入的 image標簽中 src 屬性 id 例如 <img src=“cid:image1”/>
  2. 設置MimeMessageHelper通過addInline 將cid 和文件資源進行指定即可

具體代碼如下:

package cn.lijunkui.mail;public class InlineResource {private String cid;private String path;public String getCid() {return cid;}public void setCid(String cid) {this.cid = cid;}public String getPath() {return path;}public void setPath(String path) {this.path = path;}public InlineResource(String cid, String path) {super();this.cid = cid;this.path = path;}
}/*** 發送靜態資源(一般是圖片)的郵件* @param to* @param subject* @param content 郵件內容,需要包括一個靜態資源的id,比如:<img src=\"cid:image\" >* @param resourceist 靜態資源list*/public void sendInlineResourceMail(String to, String subject, String content,List<InlineResource> resourceist){MimeMessage message = sender.createMimeMessage();try {//true表示需要創建一個multipart messageMimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(formMail);helper.setTo(to);helper.setSubject(subject);helper.setText(content, true);for (InlineResource inlineResource : resourceist) {FileSystemResource res = new FileSystemResource(new File(inlineResource.getPath()));helper.addInline(inlineResource.getCid(),res);}sender.send(message);logger.info("嵌入靜態資源的郵件已經發送。");} catch (MessagingException e) {logger.error("發送嵌入靜態資源的郵件時發生異常!", e);}}

發送帶附件的郵件

發送帶附件的郵件和發送html 操作基本一致,通過MimeMessageHelper設置郵件信息的時候,將附件通過FileSystemResource 進行包裝,然后再通過 MimeMessageHelper addAttachment 設置到發送郵件信息中即可。

具體代碼如下:

 public void sendAttachmentsMail(String toMail,String subject,String content,String filePath) {MimeMessage message = sender.createMimeMessage();try {MimeMessageHelper helper = new MimeMessageHelper(message, true);helper.setFrom(formMail);helper.setTo(toMail);helper.setSubject(subject);helper.setText(content, true);FileSystemResource file = new FileSystemResource(new File(filePath));String fileName = filePath.substring(filePath.lastIndexOf("/"));helper.addAttachment(fileName, file);sender.send(message);logger.info("發送給"+toMail+"帶附件的郵件已經發送。");} catch (MessagingException e) {e.printStackTrace();logger.error("發送給"+toMail+"帶附件的郵件時發生異常!", e);}}

測試

發送普通的郵件測試

在開發中建議大家將每個編寫完的小功能進行測試 養成良好的開發習慣。

測試用例:

package cn.lijunkui.mail;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;@SpringBootTest
@RunWith(SpringRunner.class)
public class MailServiceTest {@Autowiredprivate MailService mailService;@Testpublic void sendSimpleMail() {mailService.sendSimpleMail("1165904938@qq.com", "這是一個測試郵件", "這是一個測試郵件");}}

測試結果:
在這里插入圖片描述

發送 html 格式郵件測試

@Testpublic void snedHtmlMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + "	<font color=\"red\">發送html</font>\r\n" + "</body>\r\n" + "</html>";mailService.sendHtmlMail("1165904938@qq.com", "這是一個測試郵件", html);}

發送 html 中帶圖片的郵件測試

測試用例:

@Testpublic void sendInlineResourceMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + "<img src=\"cid:image1\"/> "+"<img src=\"cid:image2\"/> "+"	<font color=\"red\">發送html</font>\r\n" + "</body>\r\n" + "</html>";List<InlineResource> list = new ArrayList<InlineResource>();String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();InlineResource resource = new InlineResource("image1",path);InlineResource resource2 = new InlineResource("image2",path);list.add(resource2);list.add(resource);mailService.sendInlineResourceMail("1165904938@qq.com", "這是一個測試郵件", html,list);}

測試結果:
在這里插入圖片描述

發送帶附件的郵件測試

測試用例:

	@Testpublic void sendAttachmentsMail() {String html= "<!DOCTYPE html>\r\n" + "<html>\r\n" + "<head>\r\n" + "<meta charset=\"UTF-8\">\r\n" + "<title>Insert title here</title>\r\n" + "</head>\r\n" + "<body>\r\n" + "	<font color=\"red\">發送html</font>\r\n" + "</body>\r\n" + "</html>";String path = MailServiceTest.class.getClassLoader().getResource("image.jpg").getPath();mailService.sendAttachmentsMail("1165904938@qq.com", "這是一個測試郵件", html, path);}

測試結果:
在這里插入圖片描述

小結

發送普通郵件通過 SimpleMailMessage 封裝發送郵件的消息,發送 html 格式和附件郵件通過MimeMessageHelper 封裝發送郵件的消息,最后通過 JavaMailSender 的send方法進行發送即可。如果你還沒有操作過,還等什么趕緊操作一遍吧。

代碼示例

我本地環境如下:

  • SpringBoot Version: 2.1.0.RELEASE
  • Apache Maven Version: 3.6.0
  • Java Version: 1.8.0_144
  • IDEA:Spring Tools Suite (STS)

整合過程如出現問題可以在我的GitHub 倉庫 springbootexamples 中模塊名為 spring-boot-2.x_mail 項目中進行對比查看

GitHub:https://github.com/zhuoqianmingyue/springbootexamples

參考文獻

https://docs.spring.io/spring/docs/5.0.10.RELEASE/spring-framework-reference/integration.html#mail

https://www.zydui.com/af67eV28FBQ9XAlI.html
>

相关文章:

  • vscode搭建nodejs環境,關于VS code ESP-IDF 提示“loading ‘build.ninja‘: 系統找不到指定的文件” 的解決方案
  • 什么是應用軟件并舉例,16.應用舉例
  • 【面經】美團春招三輪面經分享~涵蓋眾多知識點
  • 2021年面試題目,面試題--新增
  • magic king怎么讀,magick++ 簡介
  • 微信怎么設置定時發送,朋友圈可以定時發送嗎?
  • can not connect to rpc service,RPC service
  • ftpserver安卓版,FTPServer
  • server u使用教程,Server-U
  • rpc服務器,RPC 和 Web Service 有什么區別?
  • rpc服務器,web service和rpc的區別
  • psexec
  • dhclient命令,hpe?3par命令行查看狀況腳本
  • hp存儲默認管理口地址,HP3par 多路徑存儲磁盤使用方法
  • hp3par命令行手冊,3par命令集
  • 存儲器芯片的地址范圍,存儲器芯片類別有哪些?
  • 在pc機中各類存儲器,1.14各類存儲器芯片
  • 存儲芯片漲價最新消息,存儲器芯片
  • Windows/Linux性能監控軟件>csv文件,方便生成圖表
  • sqlserver nvarchar,【SQL開發實戰技巧】系列(四十五):Oracle12C常用新特性?VARCHAR2/NVARCHAR2類型最大長度由40
  • arcgis怎么導入地圖,Arcgis路網導入3dmax批量改成道路面
  • 定義animal父類,定義一個父類Animal eat方法 , 定義兩個子類 Dog 特有方法keepHome , Cat 特有方法 catchMouse ;并
  • 手機連接兩個藍牙方法,打開藍牙的設置
  • iconfont圖標免費嗎,關于阿里矢量圖標彩色icon使用
  • ps制作賽博朋克風格,如何用ps做出賽博朋克的風格?
  • ue4綠幕實時導入場景,如何在UE4中制作賽博朋克LED效果
  • 產品經理有哪些培訓課程,2023年全國NPDP產品經理國際認證火熱招生啦
  • B端產品需要什么能力,NPDP認證|B端產品經理是如何做競品調研的?
  • 超級工具,Supershell 一款牛叉閃閃的工具
  • buffer在c語言中是什么意思,QBuffer 用法理解