1. 程式人生 > >springboot 傳送郵件+模板+附件

springboot 傳送郵件+模板+附件

package com.example.demo;

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.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.test.context.junit4.SpringRunner;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.context.IContext;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SendMailWithTemplate {
@Autowired
JavaMailSender javaMailSender;

@Autowired
TemplateEngine templateEngine;

@Test
public void sendMailWithTempalte() throws MessagingException {
MimeMessage mailMessage = javaMailSender.createMimeMessage();
//開啟帶附件true
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
// 宣告一個上下文物件,裡面放入要存到模板裡面的資料
IContext context = new Context();
//獲取模板html程式碼
((Context) context).setVariable("username", "alex");
// 指定相應的模板,然後給context資料傳過去
String process = templateEngine.process("index", context);

try {
messageHelper.setFrom("
[email protected]
");
messageHelper.setTo("[email protected]");
// 抄送
// String[] mails= new String[]{};
// messageHelper.setCc(mails);
// 密送
// messageHelper.setBcc();
messageHelper.setSubject("tempalte 模板郵件");
// 設定處理好的結果,本質就是讀取內容然後 後面一個引數html:true必須為true,保證正常的讀取hml

messageHelper.setText(process, true);
// 傳送模板的時候,同時帶附件過去
FileSystemResource fileSystemResource = new FileSystemResource("src/main/resources/static/images/a.jpg");
messageHelper.addAttachment("b.jpg", fileSystemResource);
} catch (MessagingException e) {
e.printStackTrace();
}

javaMailSender.send(mailMessage);
}
}