准备
进入qq邮箱,进行如下操作:
Do
第一步:引入依赖
<!--email-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<!--freemarker-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
第二步:配置
#配置Freemarker
# 是否开启Freemarker缓存,本地为false,生产建议为true
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.allow-request-override=false
spring.freemarker.check-template-location=true
#类型
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
#文件后缀
spring.freemarker.suffix=.ftl
#路径
spring.freemarker.template-loader-path=classpath:/templates/
#MailProperties
spring.mail.host=smtp.qq.com
spring.mail.port=465
spring.mail.username=****@qq.com
spring.mail.password=*****
spring.mail.protocol=smtps
spring.mail.properties.mail.smtp.ssl.enable=true
注意:spring.mail.password是开启QQ邮箱SMTP服务时的授权码,不是你的账号密码!!
第三步:写一个MailClient工具类
package com.activate.module.cpsp.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
/**
* @Auther:
* @Date:
* @Description: 邮件发送客户端
*/
@Component
public class MailClient {
private static final Logger logger = LoggerFactory.getLogger(MailClient.class);
@Autowired
private JavaMailSender mailSender;
@Value("${spring.mail.username}")
private String from;
/**
* 发送邮件
* @param to 收件人
* @param subject 邮件主题
* @param content 邮件内容
*/
public void sendMail(String to,String subject,String content){
try {
MimeMessage message = mailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
helper.setFrom(from);
helper.setTo(to);
helper.setSubject(subject);
// 邮件内容,第二个参数true表示支持html格式
helper.setText(content,true);
mailSender.send(helper.getMimeMessage());
} catch (MessagingException e) {
logger.error("发送邮件失败: " + e.getMessage());
}
}
}
第五步:准备一个文件模板
<!DOCTYPE html>
<html>
<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"/></head>
<div style=font-family: Arial>Dear Mr./Ms. ${username},</br>
以下为最近7天内即将到期关闭的任务,请及时关注,谢谢
</div><br>
<#list rows>
<table style=font-size:12px border=1 cellspacing=0 width=100% bordercolorlight=DarkGray bordercolordark=#efefef>
<tr><th>代码</th><th>任务名称</th><th>到期日期</th><th>剩余天数</th></tr>
<#items as row>
<tr>
<td>${row.id}</td>
<td>${row.name}</td>
<td>${row.expirydate}</td>
<td>${row.surplus}</td>
</tr>
</#items>
</table>
</#list>
<br>
<div align="right" style="font-size: 11pt;line-height:2em;" >
<strong>IT</strong><br/>
If you have any IT related questions, please send your request to
<a href='http://www.baidu.com'>Baidu.</a><br/>
<script> var day=new Date();document.write (day.toString());</script>
</div>
</html>
第六步:写一个测试类验证
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import javax.mail.internet.MimeMessage;
import java.util.*;
@SpringBootTest
public class FreeMarkerTest {
// 自动注入FreeMarker配置类,用户获取模板
@Autowired
private Configuration configuration;
// 注入Spring发送邮件的工具类
@Autowired
private JavaMailSender sender;
@Test
@DisplayName("测试freemarker")
public void test() throws Exception{
// 定义个数据根节点
Map<String,Object> root = new HashMap<>();
// 往里面塞第一层节点
root.put("UserName","xiaoming");
String[] temp = new String[]{"dog","cat","tiger"};
List<String> pets = new ArrayList<>();
Collections.addAll(pets,temp);
// 往里面塞个List对象
root.put("pets", pets);
Template template = configuration.getTemplate("helloworld.ftl");
String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, root);
System.out.println("--->"+s);
MimeMessage mimeMessage = sender.createMimeMessage();
/** 设置邮件重要性级别 */
mimeMessage.setHeader("Importance","High");
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
helper.setFrom("Intranet.FM@test.com","personalTest");
helper.setTo("Zhangsan@test.com");
helper.setSubject("This is subject 主题");
helper.setText(s,true);
sender.send(mimeMessage);
}
@Test
@DisplayName("测试邮件模板")
public void testMailFreeMark() throws Exception{
List<Map<String, String>> rows = new ArrayList<>();
Map<String, String> map = new HashMap<>();
map.put("id","314016163491");
map.put("name","小白");
map.put("expirydate","2021-04-21");
map.put("surplus","61");
Map<String, String> map2 = new HashMap<>();
map2.put("id","31400000024");
map2.put("name","小黑");
map2.put("expirydate","2021-04-22");
map2.put("surplus","2");
rows.add(map);rows.add(map2);
// 定义个数据根节点
Map<String,Object> root = new HashMap<>();
root.put("username","zhangsan");
root.put("rows",rows);
Template template = configuration.getTemplate("mailtest.ftl");
String s = FreeMarkerTemplateUtils.processTemplateIntoString(template, root);
System.out.println("--->"+s);
}
}
邮件效果: