1.先加入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
版本号自己看项目需求
2.XML文件配置
freemarker:
settings:
defaultEncoding: UTF-8
charset: UTF-8
cache: false
allow-request-override: false
expose-request-attributes: false
expose-session-attributes: false
content-type: text/html
templateLoaderPath: classpath:/template/
expose-spring-macro-helpers: false
suffix: .ftl
check-template-location: true
mail:
port: 25
username: service_searoc@163.com
password: NTBFFENKCXRJURPS
protocol: smtp
default-encoding: UTF-8
host: smtp.163.com
properties:
mail:
smtp:
ssl:
enable: false
#它是在spring级别下进行填写
(/storage/thumbnails/_signature/2R64MN8HK075K4T0OLH1S42QCP.png)
3.配置邮件.ftl文件层次对应freemarker中的templateLoaderPath路径
4.编写邮件代码,
创建一个实体类
/**
* 发送者
*/
private String from;
/**
* 接受者
*/
private String[] to;
/**
* 抄送
*/
private String[] cc;
/**
* 邮件主题
*/
private String subject;
/**
* 邮件模板
*/
private String templateName;
/**
* 模板参数
*/
private Map templateModal;
/**
* 附件
*/
private MailAttachment[] attachments;
具体实现逻辑为
public void sendMail(Mail mail) throws Exception {
MimeMessage message;
try {
message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(new InternetAddress(mail.getFrom()));
helper.setTo(mail.getTo());
helper.setSubject(mail.getSubject());
// 发送htmltext值需要给个true,不然不生效
Template template = configuration.getTemplate(mail.getTemplateName());
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, mail.getTemplateModal());
helper.setText(content, true);
if(mail.getCc() != null){
helper.setCc(mail.getCc());
}
MailAttachment[] attachments = mail.getAttachments();
if (attachments != null){
for (MailAttachment attachment : attachments) {
DataSource dataSource = new ByteArrayDataSource(attachment.getIs(), "application/" + attachment.getType());
helper.addAttachment(MimeUtility.encodeWord(attachment.getName()), dataSource);
}
}
mailSender.send(message);
}catch (Exception e){
e.printStackTrace();
throw new Exception("邮件发送失败");
}
}
5.封装mail参数
//我的邮箱(固定配置好的)、收件人,标题内容三要素
@Value("${spring.mail.username}")
private String from;
Mail mail = new Mail();
mail.setFrom(from);
mail.setTo(strings);
mail.setSubject("触发告警");
mail.setTemplateName("mail/notice.ftl");
Map data = new HashMap();
data.put("taskName", taskCreateDto);
data.put("error", s + "," + "触发告警邮件提醒");
mail.setTemplateModal(data);
return mail;
最后在通过方法调用即可.