You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot应用中使用Freemarker模板发送邮件遇TemplateNotFoundException问题求助

问题排查与解决方法

嘿,这是个典型的Freemarker配置小坑,我帮你梳理清楚:

核心问题所在

你的FreeMarkerConfigurationFactoryBean配置写错了!setTemplateLoaderPath()这个方法是用来指定模板文件所在的根目录,而不是单个模板文件的路径。

你现在设置的是"classpath:templates/email-template.ftlh",这会让Freemarker误以为模板的根目录是classpath:templates/email-template.ftlh/,然后你调用getTemplate("email-template.ftlh")时,它就会去寻找classpath:templates/email-template.ftlh/email-template.ftlh——这显然不存在,所以才抛出TemplateNotFoundException。

修正后的配置代码

把模板加载路径改成模板所在的目录就行,也就是classpath:templates/:

@Bean 
public FreeMarkerConfigurationFactoryBean getFreeMarkerConfiguration() { 
    FreeMarkerConfigurationFactoryBean fmConfigFactoryBean = new FreeMarkerConfigurationFactoryBean(); 
    // 只指定模板目录,不是具体文件
    fmConfigFactoryBean.setTemplateLoaderPath("classpath:templates/"); 
    return fmConfigFactoryBean; 
}

额外的检查要点

  • 确认模板文件名email-template.ftlh拼写完全正确,尤其是大小写(Linux/macOS环境下文件名是区分大小写的)
  • 检查打包后的项目,确保resources/templates目录和模板文件被正确复制到了classpath里(可以看target/classes/templates目录下有没有你的ftlh文件)
  • 如果你用的是Spring Boot 2.x及以上版本,其实可以不用手动配置这个Bean!Spring Boot默认会自动扫描classpath:/templates/下的Freemarker模板,你可以尝试删掉这个自定义Bean,直接用自动配置,反而更不容易出错。

内容的提问来源于stack exchange,提问作者andrew17

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 03:34:06