1. 程式人生 > >基於springboot發郵件

基於springboot發郵件

1.新增pom對郵件的支援

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

2.配置郵件引數

spring.mail.host=smtp.qq.com
[email protected]
spring.mail.password=。。。。 //授權碼
spring.mail.default-encoding=utf-8

3.傳送簡單文字郵件


	@Value("${spring.mail.username}")
	private String from; //傳送人
	
	@Autowired
	private JavaMailSender mailSender;
	
	public void sendSimpleMail(String to,String subject,String content) {
	    SimpleMailMessage simpleMailMessage = new	SimpleMailMessage();
	    simpleMailMessage.setTo(to);//接收人
	    simpleMailMessage.setSubject(subject); //郵件主題
	    simpleMailMessage.setText(content);//郵件內容
	    simpleMailMessage.setFrom(from);//傳送人
	    mailSender.send(simpleMailMessage);
	}

4.傳送帶html的郵件

public void sendHtmlMain(String to,String subject,String content) throws Exception {
		  MimeMessage mssage = mailSender.createMimeMessage();
		  MimeMessageHelper helper = new MimeMessageHelper(mssage,true);
		  helper.setTo(to);
		  helper.setSubject(subject);
		  helper.setText(content,true); //true為使用html
		  helper.setFrom(from);
		  mailSender.send(mssage);
	}


	@Test
	public void testHtmlMail() throws Exception {
		String to="
[email protected]
"; String subject="html郵件"; String content="<html>\n"+ "<body>\n"+ "<h3>hello 你好 html 郵件</h3>\n"+ "</body>\n"+ "</html>"; mailService.sendHtmlMain(to, subject, content); }

5.傳送帶有附件的郵件

	
	public void sendAttachmentsMail(String to,String subject,String content,String filePath) throws Exception {
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message,true);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content,true);
		helper.setFrom(from);

       //filepath 為附件的路徑
		FileSystemResource fileSystemResource = new FileSystemResource(new File(filePath));
		String fileName=fileSystemResource.getFilename();
		helper.addAttachment(fileName, fileSystemResource);
		mailSender.send(message);
	}


	
	//帶附件的
	@Test
	public void testAttachmentsMail() throws Exception {
		String to="[email protected]";
	   String subject="附件的郵件";
	   String content="<html>\n"+
			   "<body>\n"+
					   "<h3>hello 你好 附件 郵件</h3>\n"+
			   "</body>\n"+
				"</html>";
	   String filePath="F:\\99.GIF";
			  
		mailService.sendAttachmentsMail(to, subject, content,filePath);
	}

5.傳送html裡面有圖片的郵件

public void sendInLinResourceMail(String to,String subject,String content,String rscPath,String rscId) throws Exception {
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(message,true);
		helper.setTo(to);
		helper.setSubject(subject);
		helper.setText(content,true);
		helper.setFrom(from);
		
		FileSystemResource fileSystemResource = new FileSystemResource(new File(rscPath));
		helper.addInline(rscId, fileSystemResource);
		mailSender.send(message);
	}




	//圖片在html中的
	@Test
	public void testInLinResourceMail() throws Exception {
		String to="[email protected]";
	   String subject="圖片在html中的郵件";
	   String rscId="wq001";
	   String filePath="F:\\99.GIF";
	   String content="<html>\n"+
			   "<body>\n"+
					   "<h3>hello 圖片在html中的 郵件</h3>\n"+
			      "<img src='cid:"+rscId+"></img>"+
			   "</body>\n"+
				"</html>";
			  
		mailService.sendInLinResourceMail(to, subject, content,filePath,rscId);
	}

6. 和thymeleaf整合模板郵件

新增thymeleaf支援

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

templates資料夾下面新建 emailTemplate.html檔案

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>郵件模板</title>
</head>
<body>
這是一份註冊郵箱感謝支援,,。。。。。。。測試。。。。 點選下面的連結
<a href="#" th:href="@{http://www.baidu.com/{id}(id=${id})}">啟用賬號 </a>
</body>
</html>

test方法


	@Resource
	 TemplateEngine templateEngine;


	//模板郵件
	@Test
	public void testTmeplateMail() throws Exception {
		Context context = new Context();
		context.setVariable("id", "008");
		String emailContent=templateEngine.process("emailTemplate", context);
		
		String to="[email protected]";
		   String subject="模板中的郵件";

		mailService.sendHtmlMain(to, subject, emailContent);;
		
		
	
	}

關於異常捕獲:

private final Logger logger=(Logger) LoggerFactory.getLogger(this.getClass());

public void sendInLinResourceMail(String to,String subject,String content,String rscPath,String rscId)  {
		logger.info("開始傳送郵件。。。。{},{},{},{},{}",to,subject,content,rscPath,rscId);
		MimeMessage message = mailSender.createMimeMessage();
		MimeMessageHelper helper;
		try {
			helper = new MimeMessageHelper(message,true);
			helper.setTo(to);
			helper.setSubject(subject);
			helper.setText(content,true);
			helper.setFrom(from);
			
			FileSystemResource fileSystemResource = new FileSystemResource(new File(rscPath));
			helper.addInline(rscId, fileSystemResource);
			mailSender.send(message);
			logger.info("傳送郵件成功。。。。。。。。。");
		} catch (MessagingException e) {
			logger.error("傳送郵件失敗。。。。。。。。。");
		}
	
	}

郵件傳送到此結束

以後可以考慮 做微服務,或者放佇列