Spring FreeMarker电子邮件

时间:2013-09-22 21:51:13

标签: spring-mvc freemarker

我很难让我的SpringMVC项目使用FreeMarker。我发现this SO thread类似,但无法将实际解决方案拼凑在一起。我有一个“welcomeEmail.ftl”,我尝试放入资源/模板和src / templates,但每次我尝试运行它时都会收到错误:

java.io.FileNotFoundException: Template "welcomeEmail" not found.
    at freemarker.template.Configuration.getTemplate(Configuration.java:742)
    at freemarker.template.Configuration.getTemplate(Configuration.java:665)
    at com.xxx.utility.mail.FreemarkerFileTransformer.runTransformation(FreemarkerFileTransformer.java:44)

这是我的JavaConfig:

 @Bean
    public FreeMarkerConfigurer freemarkerConfig() {
        FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer();
        freeMarkerConfigurer.setTemplateLoaderPath( "/templates" );
        return freeMarkerConfigurer;
    }


    @Bean
    public FreeMarkerViewResolver viewResolver() {
        FreeMarkerViewResolver freeMarkerViewResolver = new FreeMarkerViewResolver();
        freeMarkerViewResolver.setSuffix( ".ftl" );
        freeMarkerViewResolver.setPrefix( "" );
        freeMarkerViewResolver.setCache( true );
        return freeMarkerViewResolver;
    }

    @Bean
    public freemarker.template.Configuration configuration() {
        freemarker.template.Configuration configuration = new freemarker.template.Configuration();
        return configuration;
    }

我尝试使用FreeMarker:

...  
private MailSender mailSender;
@Autowired
private FreemarkerFileTransformer freemarkerFileTransformer;


public void sendNewCustomerEmail(OfficeSetup officeSetup) throws Exception  {

    Map<String, String> m = new HashMap<String, String>();
    m.put("ownerName", officeSetup.getFirstName() + " " + officeSetup.getLastName());
    m.put("url", "weburl/" + officeSetup.getOfficeUrl());

    String mailContent = freemarkerFileTransformer.runTransformation(m, "", "welcomeEmail");

    SimpleMailMessage message = new SimpleMailMessage();

    message.setFrom("info@edelweissco.com");
    message.setTo(officeSetup.getUserName());
    message.setSubject("Welcome to eDentalManger, here are your activation details!");
    message.setText(mailContent);
    mailSender.send(message);

}


@Component
public class FreemarkerFileTransformer {

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private Configuration configuration;

    public String runTransformation(Map<?, ?> sourceData, String ftlTemplate) throws Exception {

        Template template = configuration.getTemplate( ftlTemplate  );
        StringWriter writer = new StringWriter();
        template.process(sourceData, writer);
        writer.flush();
        String output = writer.getBuffer().toString();
        return output;
    }

由于我只使用FreeMarker收发电子邮件,而且我没有WEB-INF目录,因此我不确定模板文件应该保存到哪里。

0 个答案:

没有答案