SpringBoot-Email郵件服務

SpringBoot中發送郵件發送功能:html

1: 引入jar包:java

<dependency><!-- 發送郵件 -->
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-mail</artifactId>
</dependency>

進行配置:git

spring:
 #郵箱配置
  mail:
    host: smtp.163.com
    username: ***********@163.com
    password: *******************
    default-encoding: UTF-8
    # 使用SMTPS協議465端口 SSL證書Socket工廠 防止公網發送失敗
    properties.mail.smtp.auth=true
    properties.mail.smtp.socketFactory.class=javax.net.ssl.SSLSocketFactory
    properties.mail.smtp.socketFactory.port=465

 

2: 定義郵件發送接口:spring

package com.gy.demo.common.config.mail;

import org.springframework.stereotype.Component;

/**
 * Description: 電子郵件接口
 *
 * @author geYang
 * @since 2017/12/27
 **/
@Component
public interface EmailService{
	
	/**
	 * TODO 發送簡單郵件(TEXT)
	 * @param to 發送地址
	 * @param subject 主題
	 * @param content 內容
	 */
	void sendSimpleMail(String to, String subject, String content);
	
	/**
	 * TODO 發送HTML郵件(頁面,不能加載圖片)
	 */
	void sendHtmlMail(String to, String subject, String content);
	/**
	 * TODO 發送附件郵件(帶文件)
	 * @param filePath 文件存放地址
	 * */
	void sendFileMail(String to, String subject, String content, String filePath);
	/**
	 * TODO 發送靜態資源郵件
	 * @param resourcePath 路徑
	 * @param resourceId   ID
	 */
	void sendStaticResourceMail(String to, String subject, String content, String resourcePath, String resourceId);
}

3: 實現apache

package com.gy.demo.common.config.mail;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * Description: 郵件發送接口實現
 *
 * @author geYang
 * @since 2017/12/27
 **/
@Component
public class EmailServiceImpl implements EmailService {
   private final Logger logger = LoggerFactory.getLogger(this.getClass());
   
   @Value("${spring.mail.username}")
   private String FROM;
   
   @Resource
   private JavaMailSender javaMailSender;
   
   /* TODO 簡單郵件發送 */
   @Override
   public void sendSimpleMail (String to, String subject, String content) {
      logger.info("發送簡單郵件");
      SimpleMailMessage message = new SimpleMailMessage();
      message.setFrom(FROM);
      message.setTo(to);
      message.setSubject(subject);
      message.setText(content);
      try{
         javaMailSender.send(message);
         logger.info("簡單郵件發送成功");
      } catch (Exception e){
         logger.error("簡單郵件發送異常!",e);
      }
   }
   
   /* TODO 發送HTML郵件 */
   @Override
   public void sendHtmlMail (String to, String subject, String content) {
      MimeMessage message = javaMailSender.createMimeMessage();
      try {
         //true表示須要建立一個 multipart message
         MimeMessageHelper helper = new MimeMessageHelper(message, true);
         helper.setFrom(FROM);
         helper.setTo(to);
         helper.setSubject(subject);
         helper.setText(content, true);
         javaMailSender.send(message);
         logger.info("HTML郵件發送成功");
      } catch (MessagingException e) {
         logger.error("HTML郵件發送異常!", e);
      }
   }
   
   /* TODO 發送帶附件郵件 */
   @Override
   public void sendFileMail (String to, String subject, String content, String filePath) {
      MimeMessage message = javaMailSender.createMimeMessage();
      try {
         MimeMessageHelper helper = new MimeMessageHelper(message, true);
         helper.setFrom(FROM);
         helper.setTo(to);
         helper.setSubject(subject);
         helper.setText(content, true);
         
         FileSystemResource file = new FileSystemResource(new File(filePath));
         String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
         helper.addAttachment(fileName, file);
         
         javaMailSender.send(message);
         logger.info("帶附件郵件發送成功");
      } catch (MessagingException e) {
         logger.error("帶附件郵件發送異常!", e);
      }
   }
   /* TODO 發送靜態資源郵件 */
   @Override
   public void sendStaticResourceMail (String to, String subject, String content, String resourcePath, String resourceId) {
      MimeMessage message = javaMailSender.createMimeMessage();
      try {
         MimeMessageHelper helper = new MimeMessageHelper(message, true);
         helper.setFrom(FROM);
         helper.setTo(to);
         helper.setSubject(subject);
         helper.setText(content, true);
         
         FileSystemResource resource = new FileSystemResource(new File(resourcePath));
         helper.addInline(resourceId, resource);
         
         javaMailSender.send(message);
         logger.info("靜態資源郵件發送成功");
      } catch (MessagingException e) {
         logger.error("靜態資源郵件發送異常!", e);
      }
   }
}

HTML模板,爲Thymelesaf:socket

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
	<meta charset="UTF-8"/>
	<title>Hello</title>
</head>
<body>
	<h1>Hello World Spring Boot</h1>
	<h2 th:text="${title}">Thymeleaf</h2>
</body>
</html>

4: 測試: ide

package com.gy.demo.common.config;

import com.gy.demo.common.config.mail.EmailService;
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;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * Description: 郵件發送測試
 *
 * @author geYang
 * @since 2017/12/27
 **/
@SpringBootTest
@RunWith(SpringRunner.class)
public class EmailTest {

	@Autowired
	private EmailService emailService;
	
	@Autowired
	private TemplateEngine templateEngine;
	
	@Test
	public void sendSimpleMailTest(){
		String to = "572119197@qq.com";
		String subject = "主題: 測試";
		String content = "內容: 測試測試";
		emailService.sendSimpleMail(to,subject,content);
	}
	
	@Test
	public void sendHtmlMailTest() {
		String to = "572119197@qq.com";
		String subject = "測試HTML郵件";
		String content = "<html><body><h1>Hello World ! 這是一封HTML郵件!</h1></body>\n</html>";
		emailService.sendHtmlMail(to,subject,content);
	}
	
	@Test
	public void sendFileMailTest(){
		String to = "572119197@qq.com";
		String subject = "測試附件";
		String content = "內容: 這是您要的文件";
		String filePath = "C:\\Users\\yvdedu.com\\Desktop\\IMGS\\image\\08.jpg";
		emailService.sendFileMail(to,subject,content,filePath);
	}
	
	@Test
	public void sendStaticResourceMailTest(){
		String to = "572119197@qq.com";
		String subject = "xxx";
		String resourceId = "my008";
		String content = "<html><body><h1>哈哈..這就是你:</h1><img src=\'cid:" + resourceId + "\' ></body></html>";
		String resourcePath = "C:\\Users\\Desktop\\IMGS\\image\\08.jpg";
		emailService.sendStaticResourceMail(to,subject,content,resourcePath,resourceId);
	}
	
	@Test
	public void sendTemplateMail() {
		Context context = new Context();
		context.setVariable("title", "geYang");
		String emailContent = templateEngine.process("index", context);
		emailService.sendHtmlMail("572119197@qq.com","主題:這是模板郵件",emailContent);
	}
	
	
	

}

    參考大神: http://www.cnblogs.com/ityouknow/category/914493.htmlspring-boot

    項目源碼: https://gitee.com/ge.yang/SpringBoot測試

相關文章
相關標籤/搜索