1. 程式人生 > >springboot2.0 快速開發郵件傳送

springboot2.0 快速開發郵件傳送

1 郵件功能開發準備

我們這裡不對官網內容做過多的闡述,直接上程式碼啦。第一個先引入mail 的start 依賴。

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

spirngboot mail 需要新增的配置資訊 我們這裡是通過yml 方式進行配置

spring:
  mail:
    host: smtp.126.com
    username: 郵箱使用者名稱
    password: 郵箱密碼
    properties:
      mail:
        smtp:
          auth: true  # 需要驗證登入名和密碼
        starttls:
          enable: true  # 需要TLS認證 保證傳送郵件安全驗證
          required: true

2 傳送普通的郵件

接下來就是我們們郵件傳送demo的正式編寫啦。spirng對傳送郵件功能進行啦封裝。 在使用的時候我們只需要定義傳送資訊到SimpleMailMessage 中 然後通過 JavaMailSender 的send 方法進行傳送即可。

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

編寫測試用例:

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

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]
", "這是一個測試郵件", "這是一個測試郵件"); } }

 測試結果:

3 傳送html格式郵件 

開發步驟:

1 通過JavaMailSender的createMimeMessage() 建立MimeMessage  物件例項

2 通過 將 MimeMessage 放入到MimeMessageHelper  建構函式中,並在 MimeMessageHelper設定傳送郵件資訊 包括 傳送人 被髮送人 主題 內容以及是否是用html

3 通過JavaMailSender 傳送 MimeMessageHelper

    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();
		}
    }
	@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);
	}

4 傳送html 中帶圖片的郵件

傳送html中帶圖片的郵件和上面傳送html郵件內容基本一致,多了一步通過MimeMessageHelper addInline 的方法

1 我們在定義html 內容是嵌入的image src 內容中制定cid 例如 <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);
        }
    }
	@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);
	}

4 傳送帶附件的郵件 

傳送帶附件的郵件和傳送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);
         }
     }

測試用例:

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