Search code examples
javaspring-bootthymeleaf

Can not set variable into thymeleaf template


I have to send email with thymeleaf template inside but I recieve clear html code without needed parameter (link). Where is my mistake?

Method:

private void sendLetter(User user, String subject, String link, String templatePath, Locale locale) {
    Context ctx = new Context(locale);
    ctx.setVariables(Collections.singletonMap("link", link));
    String htmlContent = templateEngine.process(templatePath, ctx);
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    try {
        MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        message.setTo(user.getEmail());
        message.setFrom(emailProperties.getFrom());
        message.setSubject(subject);
        message.setText(htmlContent, true);
    }
    catch (MessagingException e) {
        e.printStackTrace();
    }

    javaMailSender.send(mimeMessage);
}

Themeleaf:

<a class="main_button" href="${link}">

Solution

  • You need to use th:href instead of href.

    Change your code from

    <a class="main_button" href="${link}">
    

    to

    <a class="main_button" th:href="${link}">