我正在尝试使用Spring 4和Thymeleaf模板发送简单的HTML邮件。在我的java类中,我有:
// Prepare the evaluation context
final Context ctx = new Context(locale);
ctx.setVariable("token", token);
ctx.setVariable("serverUrl", serverUrl);
//process template
final String htmlContent = templateEngine.process("resetPassword", ctx);
templateEngine.addTemplateResolver(emailTemplateResolver);
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.javaMailSender.createMimeMessage();
MimeMessageHelper mailMessage;
try {
mailMessage = new MimeMessageHelper(mimeMessage, true, "UTF-8");
mailMessage.setTo(email);
mailMessage.setSubject("Reset password");
mailMessage.setFrom("no-reply@some.co.uk");
// Create the HTML body using Thymeleaf
mailMessage.setText(htmlContent, true);
this.javaMailSender.send(mimeMessage);
} catch (MessagingException e) {
logger.error(e.toString());
}
我的模板引擎是org.thymeleaf.spring4.SpringTemplateEngine
我也尝试过分配自定义模板引擎配置:
public ClassLoaderTemplateResolver emailTemplateResolver(){
ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
emailTemplateResolver.setPrefix("/templates/");
emailTemplateResolver.setSuffix(".html");
emailTemplateResolver.setTemplateMode("HTML5");
emailTemplateResolver.setCharacterEncoding("UTF-8");
emailTemplateResolver.setOrder(1);
return emailTemplateResolver;
}
我的HTML模板在HTML标记中包含这样的块:
th:href="#{${serverUrl}resetPassword?token=${token}}"
我希望serverUrl和token能够评估为Context变量,我已经在java代码中设置了,但我在我的电子邮件中得到了这个:
??${serverUrl}resetPassword?token=${token}_en_US??
我花了两天时间阅读关于这个主题的每一篇文章,我可以绝对保证地说,我坚持不懈。任何帮助都将受到高度赞赏。
亚历
答案 0 :(得分:1)
您正尝试使用i18n消息的语法创建链接。
而不是:
th:href="#{${serverUrl}resetPassword?token=${token}}"
使用以下内容:
th:href="@{${serverUrl} +'resetPassword'(token=${token})}"