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("wangzhilei@jd.com");
messageHelper.setTo("wangzhilei@jd.com");
// 抄送
// 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);
}
}
技术改变一切