1
我正在嘗試發送HTML電子郵件。我創建了一個模板文件,但由於它是由另一個模板解析器解決的,所以我無法弄清楚如何將我的參數傳遞給模板。如何使用上下文將參數傳遞給Thymeleaf模板?
我對模板解析器以下配置和發動機:
@Bean
public TemplateResolver templateResolver() {
TemplateResolver resolver = new ServletContextTemplateResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".html");
resolver.setCharacterEncoding("UTF-8");
resolver.setTemplateMode("HTML5");
resolver.setOrder(2);
return resolver;
}
@Bean
public TemplateResolver emailTemplateResolver() {
TemplateResolver resolver = new ClassLoaderTemplateResolver();
resolver.setPrefix("mail/");
resolver.setSuffix(".html");
resolver.setTemplateMode("HTML5");
resolver.setCharacterEncoding("UTF-8");
resolver.setOrder(1);
return resolver;
}
@Bean
public SpringTemplateEngine templateEngine() {
final SpringTemplateEngine engine = new SpringTemplateEngine();
final Set<TemplateResolver> templateResolvers = new HashSet<TemplateResolver>();
templateResolvers.add(emailTemplateResolver());
templateResolvers.add(templateResolver());
engine.setTemplateResolvers(templateResolvers);
return engine;
}
我走過時,我需要從控制器到服務模板中的所有參數。這是我用來發送電子郵件服務實現:
@Service("EmailService")
public class EmailServiceImpl implements EmailService {
@Autowired
private JavaMailSender mailSender;
@Autowired
private TemplateEngine templateEngine;
public void sendSimpleMail(final Locale locale,
final String category,
final String recipientEmail)
throws MessagingException {
// Prepare the evaluation context
final Context ctx = new Context(locale);
// Prepare message using a Spring helper
final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
final MimeMessageHelper message = new MimeMessageHelper(mimeMessage, "UTF-8");
String subject = category + " - " + result_filter;
message.setSubject(subject);
message.setTo(recipientEmail);
// Create the HTML body using Thymeleaf
final String htmlContent = this.templateEngine.process("email", ctx);
message.setText(htmlContent, true /* isHtml */);
// Send email
this.mailSender.send(mimeMessage);
}
}
這是我想使用的參數模板的一部分:
<label style="font-size: 12px;padding-bottom: 1em;" th:value="parameter">Test</label>
有沒有辦法做到這一點還是需要別的東西爲了這?
在此先感謝
是的,這正是我想做的事。非常感謝您的幫助。 – Jail
@aeseir謝謝。它的工作。爲什麼它不只與$ {parameter}一起工作?我跟着鏈接:https://memorynotfound.com/spring-mail-sending-email-thymeleaf-html-template-example/ – Krish
@Krish我有同樣的問題,遵循相同的教程。看了下面的鏈接,發現你應該使用[[$ {name}]]。 http://www.thymeleaf.org/doc/articles/thymeleaf3migration.html – shayelk