【问题标题】:How do I resolve a Thymeleaf template to send in an email?如何解析 Thymeleaf 模板以通过电子邮件发送?
【发布时间】:2021-08-25 17:32:00
【问题描述】:

我正在我的一个 Spring Boot 项目中设置电子邮件验证。我正在关注来自 baeldung 的 this tutorial。我想使用 Thymeleaf 模板发送 HTML 电子邮件。在浏览了互联网之后,我决定为我的RegistrationListener 自动装配一个SpringTemplateEngine 实例并使用它来处理模板:

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 实例,因为它需要 constructorHttpServletRequestHttpServletResponseServletContext 参数。这些对象可以在我的控制器中访问,但不能在我的事件侦听器中访问。

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

【问题讨论】:

  • 事情就是这样。像这样的相对引用在电子邮件中不起作用。 gmail 服务器不会包含bootstrap.min.css 的副本,您的电子邮件可以通过相对链接引用该副本。你必须摆脱那些参考。将 css 直接包含在文件中(在
  • @Metroids 在bootstrapemail.com 的帮助下听从您的建议,我能够得到想要的结果。如果您将您的评论作为答案,我会接受。

标签: java spring-boot spring-security thymeleaf


【解决方案1】:

/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" />
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2020-11-14
    • 1970-01-01
    • 2012-05-17
    • 2014-08-08
    • 2011-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多