Getting template text from FreeMarker in Spring app

烂漫一生 提交于 2019-11-30 03:16:24
Chris Serra

Something like this should work

Before the code you provided, initialize:

MailSender mailSender = new JavaMailSenderImpl();
SimpleMailMessage message = new SimpleMailMessage();

Then, after your code, add:

StringBuffer content = new StringBuffer();
try {
    content.append(FreeMarkerTemplateUtils.processTemplateIntoString(
        configuration.getTemplate(templateName), templateVars));
} catch (IOException e) {
    // handle
} catch (TemplateException e) {
    // handle
}

message.setFrom(getMailFromName() + " <" + getMailFromAddr() + ">");
message.setTo(getMailTo());
if (getCcTo() != null)
    message.setCc(getCcTo());
message.setSubject(getSubject());
message.setText(content.toString());

mailSender.send(message);

Here's my applicationContext.xml:

<bean id="freemarkerMailConfiguration"
  class="org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean">
    <property name="templateLoaderPath" value="/WEB-INF" />
</bean>
<bean id="yourEmailServiceClass" class="YourEmailServiceClass">
    <property name="mailSender" ref="mailSender" />
    <property name="freemarkerMailConfiguration" ref="freemarkerMailConfiguration" />
    <property name="freemarkerTemplate" value="email.ftl" />
    <property name="mailFromName" value="John Q. Programmer" />
    <property name="mailFromAddr" value="john.q.programmer@mail.com" />
    <property name="subject" value="Email Subject" />
</bean>

And your caching question...

I've only seen a bean property 'cache' in a 'viewResolver' bean, which you said you won't be using.

See also: Chapter 14. Integrating view technologies

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!