请帮我解决问题:
@Service
public class MailSenderServiceImpl implements MailSenderService {
private static final Logger logger = LoggerFactory.getLogger(MailSenderServiceImpl.class);
@Autowired
private JavaMailSender javaMailSender;
@Autowired
Configuration freemarkerConfiguration;
@Override
public void sendTemplatedEmail(String to, String from, String template, Map<String, Object> templatedMimeMessage)
throws IOException {
FileTemplateLoader templateLoader = new FileTemplateLoader(new File("src/main/resources"));
freemarkerConfiguration.setTemplateLoader(templateLoader);
MimeMessagePreparator preparator;
try {
preparator = new MimeMessagePreparator() {
// Generate a string from the template
String messageText = FreeMarkerTemplateUtils.processTemplateIntoString(
freemarkerConfiguration.getTemplate(template), templatedMimeMessage);
@Override
public void prepare(MimeMessage message) throws Exception {
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setTo(to);
helper.setFrom(from);
helper.setText(messageText, true);
}
};
Assert.notNull(javaMailSender, "javaMailSender must not be null");
this.javaMailSender.send(preparator);
} catch (Exception ex) {
logger.error("Failed to send email for templated message:" +
"\nFrom:" + from +
"\nTo:" + to +
"\nMessageMap:" + templatedMimeMessage, ex);
}
} }
这是一个集成测试:
` @Test
public void sendTemplatedEmail() throws IOException {
EmailTemplate template = createEmailTemplateObj("Test subject 111111", "Test body 11111111",
TemplateType.TENANT_CREATION);
// Send message using Free Marker template
Map<String, Object> freeMarkderTemplateMap = new HashMap<String, Object>();
freeMarkderTemplateMap.put("subject", template.getSubject());
freeMarkderTemplateMap.put("body", template.getBody());
mailSenderService.sendTemplatedEmail("test1@gmail.com", "test2@gmail.com",
"email.ftl", freeMarkderTemplateMap);
}`
我的测试没有通过,我得到模板&#34; email.ftl&#34;未找到例外,但它存在于 src / main / resources 下。我没有添加
<bean id="freeMarkerConfiguration" class="freemarker.template.Configuration" factory-bean="freeMarkerConfigurationFactory" factory-method="createConfiguration" scope="prototype"/>
在spring.xml中。假设它不是原因。
答案 0 :(得分:2)
&#34; src&#34;目录适用于开发人员工具,而不适用于正在运行的应用程序,因此您不应该使用&#34; src&#34;在你的源代码中。此外,您不是在这里加载Files
,而是加载类加载器资源,因此,请使用ClassTemplateLoader
,并指定相对于src/main/resources
的路径。因此,在您的情况下,它将是new ClassTemplateLoader(SomeClass.class, "/")
,但创建像src/main/resources/com/example/myproject/templates
这样的子目录会更好,在这种情况下,参数将为"/com/example/myproject/templates"
。
另一件事......不能在freemarkerConfiguration
中修改sendTemplatedEmail
。与任何其他单例bean一样,它应该在应用程序启动期间完全配置。