springboot mail+Thymeleaf模板

简介: compile 'org.springframework.boot:spring-boot-starter-thymeleaf' compile 'io.ratpack:ratpack-thymeleaf:1.

 

compile 'org.springframework.boot:spring-boot-starter-thymeleaf'
compile 'io.ratpack:ratpack-thymeleaf:1.4.2'

 

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import ratpack.thymeleaf.internal.ThymeleafHttpServletRequestAdapter;
import ratpack.thymeleaf.internal.ThymeleafHttpServletResponseAdapter;
import ratpack.thymeleaf.internal.ThymeleafServletContextAdapter;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * Created by hujunzheng on 17/9/8.
 */
@Service
public class MailService {

    @Autowired
    private MailProperties mailProperties;

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private TemplateEngine templateEngine;

    private static final Log log = LogFactory.getLog(MailService.class);
    /**
     * 发送邮件
     * @param userEmail
     * @param templateId
     */
    public void sendMail(String userEmail, Map<String, Object> params, int templateId) {
        sendMailMultiParams(new String[] {userEmail}, params, templateId);
    }

    public void sendMail(String userEmail, Object obj, int templateId) {
        Map<String, Object> params = objectToMap(obj);
        sendMailMultiParams(new String[] {userEmail}, params, templateId);
    }

    public void sendMail(String userEmail, String  message, String subject) {
        sendSampleMail(new String[] {userEmail}, message, subject);
    }

    public void sendMail(String[] userEmails, Map<String, Object> params, int templateId) {
        sendMailMultiParams(userEmails, params, templateId);
    }

    public void sendMail(String[] userEmails, Object obj, int templateId) {
        Map<String, Object> params = objectToMap(obj);
        sendMailMultiParams(userEmails, params, templateId);
    }

    public void sendMail(String[] userEmails, String  message, String subject) {
        sendSampleMail(userEmails, message, subject);
    }

    private Map<String, Object> objectToMap(Object obj) {
        PropertyDescriptor[] propertyDescriptors = BeanUtils.getPropertyDescriptors(obj.getClass());
        Map<String, Object> params = new HashMap<>();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Optional<Method> getter = Optional.ofNullable(property.getReadMethod());
            try {
                Object value = getter.isPresent() ? getter.get().invoke(obj) : null;
                params.put(key, value);
            } catch (ReflectiveOperationException e) {
                e.printStackTrace();
            }
        }
        return params;
    }

    /**
     * 异步 分别发送 发送邮件
    * */
    public List<String> asynSendMails(List<ApiPortalOperator> apiPortalOperators, Object bodyParams) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        List<FutureTask<String>> futureTasks = new ArrayList<>();
        for (ApiPortalOperator apiPortalOperator : apiPortalOperators) {
            FutureTask<String> futureTask = new FutureTask(() -> {
                try {
                    this.sendMail(apiPortalOperator.getEmail(), bodyParams, 1);
                } catch (Exception e) {
                    return "邮件to " + apiPortalOperator.getEmail() + " 发送异常:" + e.getMessage();
                }
                return "邮件to " + apiPortalOperator.getEmail() + " 发送成功";
            });
            futureTasks.add(futureTask);
            executorService.submit(futureTask);
        }

        List<String> result = new ArrayList<>();
        for (int i=0; i<futureTasks.size(); ++i) {
            FutureTask futureTask = futureTasks.get(i);
            try {
                result.add((String) futureTask.get());
            } catch (Exception e) {
                result.add("to " + apiPortalOperators.get(i).getEmail() + " 发送失败:" + e.getMessage());
            }
        }

        return result;
    }

    /**
     * 异步 多个收件人一起 发送邮件
     * */
    public String asynSendMail(List<ApiPortalOperator> apiPortalOperators, Object bodyParams) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        String[] userEmails = apiPortalOperators.stream().map(ApiPortalOperator::getEmail).toArray(String[]::new);
        FutureTask<String> futureTask = new FutureTask(() -> {
            try {

                this.sendMail(userEmails, bodyParams, 1);
            } catch (Exception e) {
                return "邮件to " + StringUtils.join(userEmails, ',') + " 发送异常:" + e.getMessage();
            }
            return "邮件to " + StringUtils.join(userEmails, ',') + " 发送成功";
        });
        executorService.submit(futureTask);
        try {
            return futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
            return "邮件to " + StringUtils.join(userEmails, ',') + " 发送异常:" + e.getMessage();
        }
    }

    private void sendSampleMail(String[] userEmail, String msg, String subject) {
        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "utf-8");
                message.setTo(userEmail);
                message.setFrom(new InternetAddress(mailProperties.getFrom()));
                message.setSubject(subject);
                message.setText(msg);
            }
        };
        try {
            this.javaMailSender.send(preparator);
        } catch (Exception ex) {
            log.error("Mailing Exception! user email is: {}", userEmail, ex);
        }
        log.info("Mail sent successfully, user email is: {}", userEmail);
    }

    private String buildTemplateMessage(String templateName, Map<String, Object> messages) {
        HttpServletRequest request = new ThymeleafHttpServletRequestAdapter();
        HttpServletResponse response = new ThymeleafHttpServletResponseAdapter();
        ServletContext servletContext = new ThymeleafServletContextAdapter();
        WebContext context = new WebContext(request, response, servletContext);
        context.setVariables(messages);
        return templateEngine.process(templateName, context);
    }

    /**
     * 当发邮件时有多个不定参数时
     * @param userEmail 用户邮箱
     * @param params 发邮件的参数
     * @param templateId
     */
    private void sendMailMultiParams(String[] userEmail, Map<String, Object> params, Integer templateId) {

        String templateName = MailTemplate.getTemplateName(templateId);

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "utf-8");
                message.setTo(userEmail);
                message.setFrom(new InternetAddress(mailProperties.getFrom()));
                message.setSubject(MailTemplate.getTemplateSubject(templateId));

                String content = buildTemplateMessage(templateName, params);
                System.out.println(content);
                message.setText(content, true);
            }
        };
        try {
            this.javaMailSender.send(preparator);
        } catch (Exception ex) {
            log.error("Mailing Exception! user email is: {}, template params are: {}, template_id is: {}", userEmail, params.toString(), templateId, ex);
        }
        log.info("Mail sent successfully, user email is: {}, template params: {}, template_id is: {}", userEmail, params.toString(), templateId);
    }
}

 

Thymeleaf 中有 plain context (不支持对url参数的解析)和 web context(支持对url参数的解析)

We'll have to change our code to create a web context, instead of a plain context. Change will be here: 

参考:https://github.com/ratpack/ratpack/blob/master/ratpack-thymeleaf/src/main/java/ratpack/thymeleaf/Template.java#L69-69

The IWebContext interface seems coupled to the servlet API, but after quick look at the code I don't think this will be a problem. I think we can just provide null values for things like request/session etc. that we can't provide. If that turns out to be a problem… we can look at providing implementations of those Servlet API type in so far makes sense.

 

最后附上一份简单的邮件模板文件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>邮件提醒</title>
</head>
<body style="margin: 0; padding: 0;">
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="padding: 20px; font-size: 14px;">
    <tbody>
    <tr>
        <td><p style="margin: 0; margin-bottom: 20px;">Hi,</p></td>
    </tr>
    <tr>
        <td><p style="margin: 0; margin-bottom: 20px;">项目<span th:text="${project}"/>的API已设计完成,请到<a href="#" th:href="@{ ${apiUrl} }">API Portal</a>上review。</p></td>
    </tr>
    <tr th:each="link,status : ${links}">
        <td><p style="margin: 0;"><span th:text="${status.count}"/>. <span th:text="${link.method}"/>&nbsp;<span th:text="${link.path}"/>&nbsp;<span th:text="${link.description}"/>&nbsp;<a href="#" th:href="@{ ${link.url} }">点击查看</a></p></td>
    </tr>
    <tr>
        <td><p style="margin: 0; margin-top: 20px;">Thanks</p></td>
    </tr>
    <tr>
        <td><p style="margin: 0;"><span th:text="${user}"/></p></td>
    </tr>
    </tbody>
</table>
</body>
</html>

 

目录
相关文章
|
Web App开发 XML 前端开发
Selenium安装及八大元素定位方法&介绍及使用教程
Selenium是一个支持多种编程语言的自动化测试工具,用于Web应用的测试。它提供了多种元素定位策略,包括ID、Name、Class Name、Tag Name、Link Text、Partial Link Text、CSS Selector和XPath。安装Selenium需先确保Python和pip已安装,然后通过pip安装库,并下载对应浏览器的WebDriver。验证安装成功后,可通过编写简单脚本来打开网页并打印标题。注意WebDriver版本应与浏览器兼容,且可能需要额外的依赖包。文章还介绍了XPath的两种类型及其区别,推荐使用相对XPath以提高稳定性。
1012 0
|
应用服务中间件 nginx
Nginx 服务器中设置禁止访问文件或目录的方法
Nginx 服务器中设置禁止访问文件或目录的方法
|
PyTorch 算法框架/工具
pytorch中torch.clamp()使用方法
pytorch中torch.clamp()使用方法
1912 0
pytorch中torch.clamp()使用方法
|
4天前
|
Shell API 开发工具
阿里云 DeepSeek Harness 使用教程:Cordis 插件内核剖析及框架特性、本地部署详解
DSH 的价值不在于又一个聊天窗口,而在于它把"模型能干什么"变成了可配置、可替换、可追溯的插件组合。想快速体验就直接 npx,想做二次开发就走源码,想先解决模型额度与计费问题,从 阿里云百炼大模型服务平台页面 起步最顺手。唯一要记牢的是:当前仍是开发者预览版,别把关键业务压上去。
|
11月前
|
人工智能 搜索推荐 机器人
《对话》精选|中国大模型凭何成为全球AI底座?
在“人工智能+”上升为国家战略的关键节点,央视财经频道《对话·创新中国行》,邀请到阿里云智能集团首席技术官周靖人、阿里云智能集团副总裁张亮与来自机器人、智能硬件、AIGC视频生成、AI短漫剧、教育等领域的产业先锋:科沃斯集团董事长钱东奇、自变量机器人创始人兼CEO王潜、爱诗科技创始人兼CEO王长虎、巨日禄科技创始人熊义辉、批改邦创始⼈兼CEO王庆棒展开深度对话。嘉宾们围绕“中国大模型,凭何成为全球AI底座?”这一主题共同探讨中国AI的全球竞争力,分享AI落地千行百业的丰富场景,并展望AI带来的时代变革与未来发展。完整节目已于1月25日22:16在CCTV-2及央视频同步播出。
756 1
《对话》精选|中国大模型凭何成为全球AI底座?
|
11月前
|
网络协议 前端开发 JavaScript
TCP Keepalive 与 HTTP Keep-Alive介绍与区别详解!
TCP Keepalive与HTTP Keep-Alive虽名称相似,但本质不同:前者是TCP层的连接存活探测机制,用于检测“僵死”连接;后者是HTTP层的长连接复用技术,旨在提升性能。二者分属内核与应用层,目标与实现迥异,不可混淆。
1122 10
|
8月前
|
安全 算法 API
罗兰艺境GEO数据隐私合规与脱敏治理系统:AI时代企业数据资产的安全基座
《罗兰艺境GEO数据隐私合规与脱敏治理系统》软著是“1+11”安全基座,保障数据全流程安全。核心技术:BERT+CRF敏感识别(准确率≥99%)、动态脱敏(P95≤5ms)、DCT水印(提取率≥98%)、区块链审计、合规规则引擎。为资产注入水印,支持泄露溯源。本文提供完整合规治理实践。
713 1
「AiPy实战」蚂蚁森林能量保卫战!全自动收取告别起早摸黑
AiPy 蚂蚁森林能量助手重磅上线!让手机自动帮你完成 “监控 - 收取 - 防偷” 全流程,从此告别 “能量焦虑”
|
11月前
|
弹性计算 固态存储 大数据
2026 年阿里云服务器费用详情
2026年阿里云服务器主要分为轻量应用服务器、云服务器ECS和GPU服务器三类,不同类型适配不同使用场景,费用也因配置、租期存在差异,以下是具体说明。
1067 0
|
机器学习/深度学习 人工智能 Rust
MoshiVis:语音视觉实时交互开源!7B模型秒懂图像,无障碍革命来袭
MoshiVis 是 Kyutai 推出的开源多模态语音模型,结合视觉与语音输入,支持实时交互,适用于无障碍应用、智能家居控制等多个场景。
1072 28
MoshiVis:语音视觉实时交互开源!7B模型秒懂图像,无障碍革命来袭