使用Thymeleaf发送邮件模板时标签内图片无法正常显示
问题原因
你遇到的问题是两个常见错误叠加导致的:
- 模板中使用的
${headershopgo}变量没有注入到Thymeleaf的Context中,导致模板渲染后cid:后的值为空,无法匹配到内嵌资源 - 内嵌资源添加和邮件内容设置的顺序颠倒,导致邮件客户端把内嵌资源识别为普通附件
解决方案
步骤1:补全Context变量注入
给Context添加headershopgo变量,变量值和你addInline方法的第一个参数保持一致:
Context context = new Context(); context.setVariable("name", "Volodymyr"); // 新增这行注入变量 context.setVariable("headershopgo", "headershopgo"); String process = templateEngine.process("bonnetjeEN", context);
如果不想用变量,也可以直接把模板里的th:src改写成固定值:
<img src="img/headershopgo.png" class="img-fluid " alt="header image with Aldi logo" th:src="cid:headershopgo" />
步骤2:调整方法调用顺序
先添加所有内嵌资源,再设置邮件内容,避免客户端识别错误:
// 先添加内嵌资源 helper.addInline("headershopgo",new ClassPathResource("static/img/headershopgo.png"),"image/png"); // 再设置邮件文本 helper.setText(process, true);
可选校验
如果修改后还是有问题,可以先校验资源路径是否正确,排查资源读取失败的问题:
// 运行时输出资源是否存在 System.out.println(new ClassPathResource("static/img/headershopgo.png").exists());
内容的提问来源于stack exchange,提问作者reastador
相关产品推荐
相关产品推荐

