java - 如何解析 Thymeleaf 模板以通过电子邮件发送?
问题描述
我正在我的一个 Spring Boot 项目中设置电子邮件验证。我正在学习 baeldung 的本教程。我想使用 Thymeleaf 模板发送 HTML 电子邮件。在浏览了互联网之后,我决定SpringTemplateEngine
为我自动装配一个实例RegistrationListener
并使用它来处理模板:
Context context = new Context(event.getLocale());
context.setVariable("token", token);
String html = thymeleafTemplateEngine.process("account/verify_email", context);
但是,此方法不起作用,因为我的模板引用了相关资源:
org.thymeleaf.exceptions.TemplateProcessingException: Link base "/webjars/bootstrap/5.0.1/css/bootstrap.min.css" cannot be context relative (/...) unless the context used for executing the engine implements the org.thymeleaf.context.IWebContext interface (template: "account/verify_email" - line 3, col 7)
查看异常消息,我决定探索实现IWebContext
. 最好的匹配是WebContext
。但是,我不能简单地创建一个 WebContext 实例,因为它需要构造函数HttpServletRequest
的、HttpServletResponse
和ServletContext
参数。这些对象可以在我的控制器中访问,但不能在我的事件侦听器中访问。
是否可以在事件监听器中处理我的 Thymeleaf 模板?
解决方案
像这样的相对引用/webjars/bootstrap/5.0.1/css/bootstrap.min.css
在电子邮件中根本不起作用(因为电子邮件不在原始服务器上,所以相对 css 引用没有意义)。在这种情况下,您的选择(删除相关链接后)是:
包括 css 内联:
<style> /* Put the contents of /webjars/bootstrap/5.0.1/css/bootstrap.min.css here */ </style>
直接用内联css修改标签即可:
<div style="font-family: sans-serif; color:#666666;>Your content here.../div>
将链接更改为绝对 URL(这可能会或可能不会工作,因为某些客户端删除了这些引用)。
<style href="https://yourserver/webjars/bootstrap/5.0.1/css/bootstrap.min.css" />
推荐阅读
- git - git smudge 过滤器在最后一个文件上失败
- sql - t sql 根据前一行日期值递增日期列值
- php - 无法使用 xpath 访问 XML 节点(命名空间问题?)
- android - 当应用程序未运行时,使用 Android 中的 PhoneStateListener 持续检查移动网络(2g/3g/4g)的状态(连接/断开)
- haskell - 超时时如何重试阻塞IO操作?
- amazon-web-services - 触发特定 Kinesis 事件推送的 AWS lambda
- javascript - 如果用户不确认对话框,则保留选择标签值
- sql - 过去 12 个月和单个月份的列计数
- c# - 使用 BigIntegers 的大阶乘损失精度
- jhipster - Jhipster - 更改页面标题