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

Spring Boot Thymeleaf邮件模板图片无法正常渲染问题求助

项目文件夹结构

Spring Boot Thymeleaf 邮件模板图片渲染异常解决方案

配置排查项

  • 检查application配置文件中的静态资源映射规则,默认Spring Boot会自动扫描classpath:/static/路径下的静态文件,若自定义过spring.web.resources.static-locations参数,需要将图片存放的目录路径加入配置。
    示例yml配置:
spring:
  thymeleaf:
    prefix: classpath:/templates/
    suffix: .html
    mode: HTML
    encoding: UTF-8
  web:
    resources:
      static-locations: classpath:/static/,classpath:/public/
  • 检查pom打包配置,确保静态资源没有被排除,需要将图片格式纳入打包规则:
<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <includes>
        <include>**/*.html</include>
        <include>**/*.png</include>
        <include>**/*.jpg</include>
        <include>**/*.jpeg</include>
      </includes>
    </resource>
  </resources>
</build>

模板引用写法修正

邮件客户端无法访问项目本地相对路径资源,需使用以下两种合法引用方式:

方式1:CID内嵌附件引用

  1. 发送邮件时将图片作为内嵌附件加入MimeMessage,绑定唯一Content-ID
    代码示例:
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
// 设置收件人、主题等基础信息
FileSystemResource imgRes = new FileSystemResource(new ClassPathResource("static/images/你的图片名.png").getFile());
helper.addInline("自定义的cid标识", imgRes);
// 渲染Thymeleaf模板
Context context = new Context();
String content = templateEngine.process("你的邮件模板名", context);
helper.setText(content, true);
javaMailSender.send(mimeMessage);
  1. 模板内对应写法:
<img th:src="'cid:自定义的cid标识'" alt="图片说明">

方式2:公网直链引用

将图片上传至公网可访问的存储服务,模板内直接填写完整URL:

<img th:src="@{https://你的公网资源路径/图片名.png}" alt="图片说明">

实例校验注意项

确保业务代码中使用的TemplateEngine实例是Spring容器自动注入的,不要手动new实例,避免丢失默认解析配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 16:06:04