如何在 Spring Boot 应用程序中使用 Freemarker 模板发送电子邮件?

How to send email with Freemarker template in Spring Boot app?

我正在尝试使用 Freemarker 模板发送电子邮件。

代码:

public String geContentFromTemplate(Map<String, Object> model) throws IOException, TemplateException {
        StringWriter stringWriter = new StringWriter();
        fmConfiguration.getTemplate("email-template.ftlh").process(model, stringWriter);
        return stringWriter.getBuffer().toString();
}

public void sendEmailWithTemplate(String to, String subject, User user) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {

            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);

            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setFrom(emailFrom);
            mimeMessageHelper.setTo(to);
            Map<String, Object> model = new HashMap<>();
            model.put("firstName", user.getFirstName());
            model.put("lastName", user.getLastName());
            String content = geContentFromTemplate(model);
            mimeMessageHelper.setText(content, true);

            mailSender.send(mimeMessageHelper.getMimeMessage());
        } catch (MessagingException | IOException | TemplateException e) {
            e.printStackTrace();
        }
    }

Freemarker Bean:

 @Bean
    public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() {
        FreeMarkerConfigurationFactoryBean fmConfigFactoryBean = new FreeMarkerConfigurationFactoryBean();
        fmConfigFactoryBean.setTemplateLoaderPath("classpath:templates/email-template.ftlh");
        return fmConfigFactoryBean;
    }

我的模板位于 Spring 启动应用程序:resources/templates/email-template.ftlh

我收到此异常: freemarker.template.TemplateNotFoundException: Template not found for name "email-template.ftlh". The name was interpreted by this TemplateLoader: org.springframework.ui.freemarker.SpringTemplateLoader@33cceeb3.

我通过更改@Bean 解决了这个问题。我删除了上一个并创建了另一个:

  @Bean
    public FreeMarkerConfigurer freeMarkerConfigurer(){
        freemarker.template.Configuration configuration = new freemarker.template.Configuration(freemarker.template.Configuration.VERSION_2_3_19);
        TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), "/templates/");
        configuration.setTemplateLoader(templateLoader);
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setConfiguration(configuration);
        return freeMarkerConfigurer;
    }

模板加载也是这样实现的:

            Template template = freeMarkerConfigurer.getConfiguration().getTemplate("email-template.ftlh");
            String htmlBody = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);