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

使用MimeMessageHelper发邮件时内嵌图片正常但附件不显示如何解决

问题原因

你遇到的问题是MimeMessageHelper的资源添加顺序和multipart模式配置不符合规范,导致邮件客户端无法正确区分内嵌资源和附件:

  1. 现有代码先添加附件、后设置邮件内容、最后加内嵌资源,调用顺序错误,会破坏MIME邮件的层级结构
  2. 附件文件名包含特殊字符未做编码处理,部分客户端会识别失败

解决方法

按以下步骤调整代码即可:

  1. 明确指定MimeMessageHelper的multipart模式为MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,兼容内嵌资源+附件的场景
  2. 调整调用顺序:先完成邮件头设置、渲染HTML内容并调用setText,再添加所有内嵌资源,最后添加附件
  3. 对附件文件名做编码处理,避免特殊字符解析异常

修改后参考代码如下:

import javax.mail.internet.MimeUtility;

// 构造时明确指定multipart模式
MimeMessageHelper helper = new MimeMessageHelper(mmessage, MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED, "UTF-8");
// 先设置邮件基础信息
helper.setFrom(FROM_ADRESS_DEF);
helper.setTo("****here mail*****");
helper.setSubject("Your Shop&Go Invoice");

// 渲染模板
ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
templateResolver.setPrefix("/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
templateResolver.setOrder(1);
TemplateEngine templateEngine = new TemplateEngine();
templateEngine.setTemplateResolver(templateResolver);

Context context = new Context();
context.setVariable("name", "Volodymyr");
DateTimeFormatter formater1 = DateTimeFormatter.ofPattern("dd.MM.yyyy");
context.setVariable("date", formater1.format(LocalDateTime.now()));
String process = templateEngine.process("bonnetjeEN", context);
// 先设置HTML内容
helper.setText(process, true);

// 再添加所有内嵌资源
helper.addInline("headershopgo", new ClassPathResource("static/img/headershopgo.png"));
helper.addInline("ln", new ClassPathResource("static/img/in.png"));
helper.addInline("inst", new ClassPathResource("static/img/insta.png"));
helper.addInline("fb", new ClassPathResource("static/img/fb.png"));
helper.addInline("aln", new ClassPathResource("static/img/aldi.jpg"));

// 最后添加附件,文件名做编码处理
File file = new File("C:\\Users\\redxp\\Downloads\\demo (1)\\demo\\src\\main\\resources\\file.pdf");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String fileName = "Shop & Go invoice " + LocalDateTime.now().format(formatter);
// 编码文件名避免特殊字符问题
helper.addAttachment(MimeUtility.encodeText(fileName, "UTF-8", "B"), file);

调整后邮件客户端就能正确区分内嵌资源和附件,未打开邮件时不会额外显示内嵌图片,附件也能正常加载。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 19:15:05