首页 > 解决方案 > 如何解析 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的、HttpServletResponseServletContext参数。这些对象可以在我的控制器中访问,但不能在我的事件侦听器中访问。

是否可以在事件监听器中处理我的 Thymeleaf 模板?

标签: javaspring-bootspring-securitythymeleaf

解决方案


像这样的相对引用/webjars/bootstrap/5.0.1/css/bootstrap.min.css在电子邮件中根本不起作用(因为电子邮件不在原始服务器上,所以相对 css 引用没有意义)。在这种情况下,您的选择(删除相关链接后)是:

  1. 包括 css 内联:

     <style>
     /* Put the contents of /webjars/bootstrap/5.0.1/css/bootstrap.min.css  here */
     </style>
    
  2. 直接用内联css修改标签即可:

     <div style="font-family: sans-serif; color:#666666;>Your content here.../div>
    
  3. 将链接更改为绝对 URL(这可能会或可能不会工作,因为某些客户端删除了这些引用)。

     <style href="https://yourserver/webjars/bootstrap/5.0.1/css/bootstrap.min.css" />
    

推荐阅读