签入版本
This commit is contained in:
+563
@@ -0,0 +1,563 @@
|
||||
// +======================================================================
|
||||
// | 小蚂蚁云·企业数字化开发平台 [ 加速数字化转型,构建智能未来 ]
|
||||
// +----------------------------------------------------------------------
|
||||
// | 核心价值:赋能开发者 · 服务企业 · 共建生态
|
||||
// +----------------------------------------------------------------------
|
||||
// | Copyright (c) 2020-2026 小蚂蚁云团队 版权所有
|
||||
// +----------------------------------------------------------------------
|
||||
// | 官方平台: https://www.xiaomayicloud.com
|
||||
// +======================================================================
|
||||
// | 【知识产权声明】
|
||||
// | 1. 权属声明:本软件是受《中华人民共和国著作权法》
|
||||
// | 保护的专有财产,完整版权归小蚂蚁云团队所有
|
||||
// | 2. 权利范围:所有知识产权(商标、专利、著作权、
|
||||
// | 商业秘密等)均归小蚂蚁云团队所有,受法律保护
|
||||
// | 3. 授权性质:用户仅可获得有限的、非独占的使用许可
|
||||
// | 4. 禁止行为:未经书面授权,禁止对本软件本身
|
||||
// | 申请任何知识产权
|
||||
// | 5. 权利保留:未在本协议中明示授予的一切权利
|
||||
// | 均由小蚂蚁云团队保留
|
||||
// +======================================================================
|
||||
// | 【授权状态说明】
|
||||
// | 1. 未授权状态:用户未购买有效的商业许可证
|
||||
// | 2. 商业授权:已购买正式商业许可证的用户
|
||||
// +======================================================================
|
||||
// | 【绝对禁止条款】
|
||||
// | 无论授权状态如何,任何用户均严格禁止以下行为:
|
||||
// | 1. 逆向工程:对软件进行反编译、反汇编、技术破解或任何形式的逆向分析
|
||||
// | 2. 版权破坏:移除、修改、遮挡软件中的版权标识、许可控制或技术保护措施
|
||||
// | 3. 非法传播:复制、分发、出租、出借、转售、再许可本软件或其许可权利
|
||||
// | 4. 竞争性使用:利用本软件的代码、架构、设计开发直接竞争的产品或服务
|
||||
// | 5. 侵权使用:将软件用于侵犯第三方知识产权或其他合法权益的用途
|
||||
// +======================================================================
|
||||
// | 【商业授权许可范围】
|
||||
// | 购买有效商业许可证的用户,在遵守上述禁止条款的前提下,获得:
|
||||
// | 1. 使用权利:在许可证约定的项目数量、开发者数量范围内使用本软件
|
||||
// | 2. 技术支持:商业授权用户可以获取本地开发部署的技术支持服务
|
||||
// | 3. 版本更新:在许可证有效期内获取软件更新、安全补丁和功能增强
|
||||
// | 4. 商业部署:将基于本软件开发的应用程序用于商业运营和生产环境
|
||||
// +======================================================================
|
||||
// | 【许可证获取】
|
||||
// | 1. 获取途径:仅通过小蚂蚁云官方渠道购买(官网、授权代理商),购买记录凭证
|
||||
// | 2. 转让限制:许可证与购买主体绑定,未经书面同意不得转让
|
||||
// | 3. 终止情形:许可证到期、违反协议、破产清算等情况下自动终止
|
||||
// +======================================================================
|
||||
// | 【合法使用要求】
|
||||
// | 1. 仅限用于合法合规的软件研发
|
||||
// | 2. 严禁用于任何违法、侵权或恶意行为
|
||||
// | 3. 严禁违反我国法律法规和政策
|
||||
// +======================================================================
|
||||
// | 【免责声明】
|
||||
// | 因使用本框架导致的以下情况,我们概不负责:
|
||||
// | 1. 项目研发中的意外、疏忽、违约等风险
|
||||
// | 2. 侵犯第三方知识产权或其他合法权益
|
||||
// | 3. 任何直接、间接、附带或衍生一切损失
|
||||
// | 4. 用户违规违法行为的一切法律后果
|
||||
// +======================================================================
|
||||
// | 【协议重要提示】
|
||||
// | 1. 本声明是《小蚂蚁云最终用户许可协议》的摘要版本
|
||||
// | 2. 下载、安装或使用本软件即表示您接受全部协议条款
|
||||
// | 3. 我们保留单方面修改本声明的权利,修改后的版本在官网公布即生效
|
||||
// | 4. 用户有义务定期查看最新版本,继续使用视为接受修改
|
||||
// +======================================================================
|
||||
// | 【侵权举报与合规】
|
||||
// | 1. 知识产权侵权举报:请联系官方客服
|
||||
// | 2. 许可证合规咨询:xiaomayicloud@163.com
|
||||
// | 3. 违规使用将终止授权并追究责任
|
||||
// | 4. 无条件配合司法机关调查取证
|
||||
// | 5. 保留一切法律追诉权利
|
||||
// | 6. 对有效举报和合规建议,我们将给予感谢和奖励
|
||||
// +======================================================================
|
||||
|
||||
package com.xiaomayi.email.utils;
|
||||
|
||||
import com.xiaomayi.core.config.AppConfig;
|
||||
import com.xiaomayi.core.utils.CommonUtils;
|
||||
import com.xiaomayi.core.utils.StringUtils;
|
||||
import com.xiaomayi.email.config.EmailConfig;
|
||||
import com.xiaomayi.email.dto.EmailSendDTO;
|
||||
import jakarta.mail.MessagingException;
|
||||
import jakarta.mail.internet.MimeMessage;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.text.StringSubstitutor;
|
||||
import org.springframework.context.annotation.DependsOn;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.mail.SimpleMailMessage;
|
||||
import org.springframework.mail.javamail.JavaMailSenderImpl;
|
||||
import org.springframework.mail.javamail.MimeMessageHelper;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.thymeleaf.TemplateEngine;
|
||||
import org.thymeleaf.context.Context;
|
||||
import org.thymeleaf.templatemode.TemplateMode;
|
||||
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;
|
||||
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.text.MessageFormat;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* 电子邮件工具类
|
||||
* </p>
|
||||
*
|
||||
* @author 小蚂蚁云团队
|
||||
* @since 2024-06-16
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@AllArgsConstructor
|
||||
@DependsOn("emailConfig")
|
||||
public class EmailUtils {
|
||||
|
||||
private static TemplateEngine templateEngine;
|
||||
|
||||
private static JavaMailSenderImpl mailSender;
|
||||
|
||||
private static final Pattern PLACEHOLDER_PATTERN = Pattern.compile("\\$\\{(\\w+)\\}");
|
||||
|
||||
static {
|
||||
// 创建模板解析器
|
||||
ClassLoaderTemplateResolver resolver = new ClassLoaderTemplateResolver();
|
||||
// 模板路径(resources目录下)
|
||||
resolver.setPrefix("/templates/");
|
||||
resolver.setSuffix(".html");
|
||||
resolver.setTemplateMode(TemplateMode.HTML);
|
||||
resolver.setCharacterEncoding("UTF-8");
|
||||
|
||||
// 初始化模板引擎
|
||||
templateEngine = new TemplateEngine();
|
||||
templateEngine.setTemplateResolver(resolver);
|
||||
}
|
||||
|
||||
static {
|
||||
// 打印邮箱配置信息到日志
|
||||
log.info("邮箱主机:" + EmailConfig.getHost());
|
||||
log.info("邮箱端口:" + EmailConfig.getPort());
|
||||
log.info("邮箱账号:" + EmailConfig.getUsername());
|
||||
log.info("邮箱密码:" + EmailConfig.getPassword());
|
||||
|
||||
// 创建 JavaMailSender 实例
|
||||
mailSender = new JavaMailSenderImpl();
|
||||
// 设置邮件服务器主机地址
|
||||
mailSender.setHost(EmailConfig.getHost());//链接服务器
|
||||
// 设置邮件服务器端口号
|
||||
mailSender.setPort(EmailConfig.getPort());
|
||||
// 设置发件人邮箱账号
|
||||
mailSender.setUsername(EmailConfig.getUsername());
|
||||
// 设置发件人邮箱密码或授权码
|
||||
mailSender.setPassword(EmailConfig.getPassword());
|
||||
// 设置默认编码格式为UTF-8,防止中文乱码
|
||||
mailSender.setDefaultEncoding("UTF-8");
|
||||
// 创建邮件会话属性配置对象
|
||||
Properties properties = new Properties();
|
||||
// 开启SMTP认证,必须提供用户名和密码才能发送邮件
|
||||
properties.setProperty("mail.smtp.auth", "true");
|
||||
// 启用调试模式,会在控制台打印详细的邮件发送过程信息
|
||||
properties.setProperty("mail.debug", "true");
|
||||
// 设置邮件发送超时时间为1000毫秒(1秒)- 这个值可能太短,建议增加到30000毫秒
|
||||
properties.setProperty("mail.smtp.timeout", "30000");
|
||||
// 设置SMTP协议使用的端口号
|
||||
properties.setProperty("mail.smtp.port", String.valueOf(EmailConfig.getPort()));//设置端口
|
||||
// 设置SSL socket工厂使用的端口号
|
||||
properties.setProperty("mail.smtp.socketFactory.port", String.valueOf(EmailConfig.getPort()));//设置ssl端口
|
||||
// 设置不使用回退机制,如果SSL连接失败不会回退到非SSL连接
|
||||
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
|
||||
// 指定使用SSL socket工厂类来创建安全的SSL连接
|
||||
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
|
||||
// 将配置属性应用到邮件发送器
|
||||
mailSender.setJavaMailProperties(properties);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送邮件
|
||||
* 备注:支持资源HTML模板、自定义HTML模板、普通文本、邮件附件
|
||||
*
|
||||
* @param emailSendDTO 参数
|
||||
* @return 返回结果
|
||||
*/
|
||||
public static boolean sendEMail(EmailSendDTO emailSendDTO) {
|
||||
// 邮件主题
|
||||
String subject = emailSendDTO.getTitle();
|
||||
// 邮件内容
|
||||
String content = emailSendDTO.getContent();
|
||||
// 接收人邮箱
|
||||
String to = emailSendDTO.getEmail();
|
||||
|
||||
log.info("发送Template邮件开始:{},{}", to, subject);
|
||||
|
||||
if (StringUtils.isNotEmpty(to)) {
|
||||
log.info("=================== 发送邮件开始 ================");
|
||||
|
||||
// 模板参数
|
||||
Map<String, Object> params = emailSendDTO.getParams();
|
||||
if (StringUtils.isNotEmpty(params)) {
|
||||
// 模板文件
|
||||
String tplPath = emailSendDTO.getTplPath();
|
||||
// 模板邮件
|
||||
if (StringUtils.isNotEmpty(tplPath)) {
|
||||
try {
|
||||
if (emailSendDTO.getIsTemplate()) {
|
||||
// 利用 Thymeleaf 模板构建 html 文本
|
||||
Context context = new Context();
|
||||
for (Map.Entry<String, Object> entry : params.entrySet()) {
|
||||
// 给模板参数变量赋值
|
||||
context.setVariable(entry.getKey(), entry.getValue());
|
||||
}
|
||||
// 执行模板引擎,执行模板引擎需要传入模板名、上下文对象
|
||||
// Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
|
||||
content = templateEngine.process(tplPath, context);
|
||||
} else {
|
||||
// 调用模板构建内容
|
||||
content = EmailUtils.buildContent(tplPath, params);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
// 普通文本邮件
|
||||
else {
|
||||
// 参数格式化
|
||||
StringSubstitutor stringSubstitutor = new StringSubstitutor(params);
|
||||
// 内容参数替换,此处基于依赖commons-text
|
||||
content = stringSubstitutor.replace(content);
|
||||
}
|
||||
// 反向赋值便于邮件日志存储记录
|
||||
emailSendDTO.setContent(content);
|
||||
}
|
||||
|
||||
// 使用MimeMessage,MIME协议
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper messageHelper;
|
||||
try {
|
||||
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
messageHelper.setFrom(EmailConfig.getUsername());
|
||||
messageHelper.setTo(to);
|
||||
messageHelper.setSubject(subject);
|
||||
// true代表支持html,false,显示原始html代码,无效果
|
||||
messageHelper.setText(content, true);
|
||||
// 抄送人
|
||||
if (StringUtils.isNotEmpty(emailSendDTO.getCcEmail())) {
|
||||
messageHelper.setCc(emailSendDTO.getCcEmail());
|
||||
}
|
||||
|
||||
// 附件资源处理
|
||||
List<String> attachment = emailSendDTO.getAttachment();
|
||||
if (StringUtils.isNotEmpty(attachment)) {
|
||||
// 遍历附件资源
|
||||
for (String filePath : attachment) {
|
||||
// 创建附件资源
|
||||
FileSystemResource file = new FileSystemResource(filePath);
|
||||
// 文件不存在,直接跳过
|
||||
if (!file.exists()) {
|
||||
continue;
|
||||
}
|
||||
// 获取附件文件名
|
||||
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
|
||||
// 加入附件
|
||||
messageHelper.addAttachment(fileName, file);
|
||||
}
|
||||
}
|
||||
mailSender.send(message);
|
||||
log.info("邮件发送成功");
|
||||
return true;
|
||||
} catch (MessagingException e) {
|
||||
log.error("邮件发送失败:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送纯文字邮件
|
||||
*
|
||||
* @param to 收件人
|
||||
* @param subject 邮件主题
|
||||
* @param content 邮件内容
|
||||
*/
|
||||
public static void sendSimpleMail(String to, String subject, String content) {
|
||||
// 开启线程异步发送邮件,防止发送请求时间过长造成阻塞
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// 创建SimpleMailMessage对象
|
||||
SimpleMailMessage message = new SimpleMailMessage();
|
||||
// 邮件发送人
|
||||
message.setFrom(EmailConfig.getUsername());
|
||||
// 邮件接收人
|
||||
message.setTo(to);
|
||||
// 邮件主题
|
||||
message.setSubject(subject);
|
||||
// 邮件内容
|
||||
message.setText(content);
|
||||
// 发送邮件
|
||||
try {
|
||||
mailSender.send(message);
|
||||
log.info("邮件接收人" + to + "主题" + subject + "内容" + content + "邮件发送成功");
|
||||
} catch (Exception e) {
|
||||
log.error("邮件接收人" + to + "主题" + subject + "内容" + content + "邮件发送出现异常");
|
||||
log.error("异常信息为" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送简单邮件
|
||||
*
|
||||
* @param to 收件人
|
||||
* @param subject 邮件主题
|
||||
* @param content 邮件内容
|
||||
*/
|
||||
public static void sendMail(String to, String subject, String content) {
|
||||
MimeMessage message;
|
||||
try {
|
||||
// 创建邮件消息
|
||||
message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper = new MimeMessageHelper(message, true);
|
||||
// 发送者
|
||||
helper.setFrom(EmailConfig.getUsername());
|
||||
// 接收者
|
||||
helper.setTo(to);
|
||||
// 邮件主题
|
||||
helper.setSubject(subject);
|
||||
// 设置邮件内容
|
||||
helper.setText(content, true);
|
||||
// 发送邮件
|
||||
mailSender.send(message);
|
||||
log.info("邮件发送成功");
|
||||
} catch (MessagingException e) {
|
||||
log.error("邮件发送失败:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送HTML模板邮件
|
||||
*
|
||||
* @param params 邮件模板参数
|
||||
* @param tplPath 邮件模板路径
|
||||
* @return 返回结果
|
||||
*/
|
||||
public static String buildContent(Object[] params, String tplPath) {
|
||||
try {
|
||||
// 加载邮件html模板
|
||||
Resource resource = new ClassPathResource(String.format("/templates/%s", tplPath));
|
||||
// 创建输入流
|
||||
InputStream inputStream = resource.getInputStream();
|
||||
BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
// 实例化构建器
|
||||
StringBuilder buffer = new StringBuilder();
|
||||
// 逐行读取
|
||||
String line = "";
|
||||
try {
|
||||
while ((line = fileReader.readLine()) != null) {
|
||||
buffer.append(line);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("读取文件失败:{}", e.getMessage());
|
||||
} finally {
|
||||
inputStream.close();
|
||||
fileReader.close();
|
||||
}
|
||||
// 返回结果
|
||||
return MessageFormat.format(buffer.toString(), params);
|
||||
} catch (Exception e) {
|
||||
log.error("发送邮件异常:{}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件系统加载模板并替换占位符
|
||||
*
|
||||
* @param templatePath 模板文件完整路径
|
||||
* @param parameters 替换参数Map
|
||||
* @return 处理后的模板内容
|
||||
* @throws IOException 异常处理
|
||||
*/
|
||||
public static String buildContent(String templatePath, Map<String, Object> parameters) throws IOException {
|
||||
// 读取模板
|
||||
String templateContent = loadTemplate(templatePath);
|
||||
// 绑定数据
|
||||
return bindVariables(templateContent, parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载模板文件内容
|
||||
*
|
||||
* @param filePath 完整文件路径
|
||||
* @return 模板内容
|
||||
* @throws IOException 异常处理
|
||||
*/
|
||||
public static String loadTemplate(String filePath) throws IOException {
|
||||
// 文件路径
|
||||
if (!filePath.contains(AppConfig.getProfile())) {
|
||||
filePath = CommonUtils.getFilePath(filePath);
|
||||
}
|
||||
// 文件模板路径
|
||||
Path path = Paths.get(filePath);
|
||||
if (!Files.exists(path)) {
|
||||
throw new IOException("模板文件不存在: " + filePath);
|
||||
}
|
||||
// 读取文件模板
|
||||
try (BufferedReader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
|
||||
StringBuilder content = new StringBuilder();
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
content.append(line).append("\n");
|
||||
}
|
||||
return content.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定变量到模板
|
||||
*
|
||||
* @param template 模板内容
|
||||
* @param parameters 参数
|
||||
* @return 返回结果
|
||||
*/
|
||||
private static String bindVariables(String template, Map<String, Object> parameters) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
Matcher matcher = PLACEHOLDER_PATTERN.matcher(template);
|
||||
|
||||
while (matcher.find()) {
|
||||
String placeholder = matcher.group(1);
|
||||
Object value = parameters.getOrDefault(placeholder, "");
|
||||
matcher.appendReplacement(result, Matcher.quoteReplacement(value.toString()));
|
||||
}
|
||||
matcher.appendTail(result);
|
||||
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送带附件的邮件
|
||||
*
|
||||
* @param to 收件人
|
||||
* @param subject 邮件主题
|
||||
* @param content 邮件内容
|
||||
* @param filePath 附件路径
|
||||
*/
|
||||
public static void sendAttachmentMail(String to, String subject, String content, String filePath) {
|
||||
log.info("发送带附件的邮件:{},{},{},{}", to, subject, content, filePath);
|
||||
// 开启线程异步发送邮件,防止发送请求时间过长造成阻塞
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (StringUtils.isNotEmpty(to)) {
|
||||
log.info("=================== 发送邮件开始 ================");
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper messageHelper;
|
||||
try {
|
||||
messageHelper = new MimeMessageHelper(message, true, "UTF-8");
|
||||
messageHelper.setFrom(EmailConfig.getUsername());
|
||||
messageHelper.setTo(to);
|
||||
messageHelper.setSubject(subject);
|
||||
messageHelper.setText(content, true);
|
||||
// 创建附件资源
|
||||
FileSystemResource file = new FileSystemResource(filePath);
|
||||
String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
|
||||
messageHelper.addAttachment(fileName, file);
|
||||
// 发送邮件
|
||||
mailSender.send(message);
|
||||
log.info("邮件发送成功!");
|
||||
} catch (MessagingException e) {
|
||||
log.error("邮件发送失败:{}" + e.getMessage());
|
||||
}
|
||||
log.info("=================== 发送邮件结束 ================");
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送图片邮件
|
||||
*
|
||||
* @param to 收件人
|
||||
* @param subject 邮件主题
|
||||
* @param content 邮件内容
|
||||
* @param rscPath 图片路径
|
||||
* @param rscId 图片ID
|
||||
*/
|
||||
public static void sendInlineMail(String to, String subject, String content, String rscPath, String rscId) {
|
||||
// 开启线程异步发送 防止发送请求时间过长
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
log.info("发送带图片邮件开始:{},{},{},{},{}", to, subject, content, rscPath, rscId);
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper;
|
||||
try {
|
||||
helper = new MimeMessageHelper(message, true);
|
||||
helper.setFrom(EmailConfig.getUsername());
|
||||
helper.setTo(to);
|
||||
helper.setSubject(subject);
|
||||
helper.setText(content, true);
|
||||
helper.setSentDate(new Date());
|
||||
FileSystemResource res = new FileSystemResource(new File(rscPath));
|
||||
// 重复使用添加多个图片
|
||||
helper.addInline(rscId, res);
|
||||
mailSender.send(message);
|
||||
log.info("发送带图片邮件成功");
|
||||
} catch (MessagingException e) {
|
||||
log.error("发送带图片邮件失败:", e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送HTML模板邮件
|
||||
*
|
||||
* @param to 收件人
|
||||
* @param subject 邮件主题
|
||||
* @param tplPath 模板路径
|
||||
* @param map 模板数据
|
||||
*/
|
||||
public void sendTemplateMail(String to, String subject, String tplPath, Map<String, Object> map) {
|
||||
// 开启线程异步发送 防止发送请求时间过长
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
log.info("发送Template邮件开始:{},{},{}", to, subject, tplPath);
|
||||
// 利用 Thymeleaf 模板构建 html 文本
|
||||
Context context = new Context();
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
// 给模板参数变量赋值
|
||||
context.setVariable(entry.getKey(), entry.getValue());
|
||||
}
|
||||
// 执行模板引擎,执行模板引擎需要传入模板名、上下文对象
|
||||
// Thymeleaf的默认配置期望所有HTML文件都放在 **resources/templates ** 目录下,以.html扩展名结尾。
|
||||
String content = templateEngine.process(tplPath, context);
|
||||
|
||||
// 使用MimeMessage,MIME协议
|
||||
MimeMessage message = mailSender.createMimeMessage();
|
||||
MimeMessageHelper helper;
|
||||
try {
|
||||
helper = new MimeMessageHelper(message, true);
|
||||
helper.setFrom(EmailConfig.getUsername());
|
||||
helper.setTo(to);
|
||||
helper.setSubject(subject);
|
||||
// true代表支持html
|
||||
helper.setText(content, true);
|
||||
mailSender.send(message);
|
||||
log.info("发送模板邮件成功");
|
||||
} catch (MessagingException e) {
|
||||
log.error("发送模板邮件失败:", e);
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user