玩轉 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.com
    username: 郵箱用戶名
    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());
	
    @Autowired
    private 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 message
            MimeMessageHelper 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 {
	@Autowired
	private MailService mailService;
	
	@Test
	public void sendSimpleMail() {
		mailService.sendSimpleMail("[email protected]", "這是一個測試郵件", "這是一個測試郵件");
	}
	
}

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

發送 html 格式郵件測試

@Test
	public 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("[email protected]", "這是一個測試郵件", html);
	}

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

測試用例:

@Test
	public 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("[email protected]", "這是一個測試郵件", html,list);
	}

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

發送帶附件的郵件測試

測試用例:

	@Test
	public 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("[email protected]", "這是一個測試郵件", 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章