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

如何通过Apache Velocity与JavaMail添加图片为内嵌附件

解决Spring邮件嵌入本地图片(配合Velocity模板)的方案

我来帮你搞定这个问题!你已经在Velocity模板里配置了cid引用,接下来只需要在Spring邮件工具类里完成本地图片加载和cid绑定,同时把cid变量传递给模板上下文就行,咱们一步步来:

1. 完善sendOrderMail异步方法的实现

结合Spring的JavaMailSender和Velocity模板,下面是完整的可运行代码示例:

import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.ui.velocity.VelocityEngineUtils;
import org.springframework.core.io.FileSystemResource;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

// 注意确保JavaMailSender和VelocityEngine已通过@Autowired注入
@Async
public void sendOrderMail(String emailAddress, String imageFileName) throws MessagingException {
    // 1. 读取本地图片资源
    String localImagePath = "/tmp/upload/image/" + imageFileName;
    File imageFile = new File(localImagePath);
    FileSystemResource imageResource = new FileSystemResource(imageFile);
    
    // 2. 创建支持内嵌资源的MIME邮件
    MimeMessage mimeMessage = javaMailSender.createMimeMessage();
    // 开启multipart模式(必须传true),支持HTML和内嵌资源
    MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
    
    // 3. 设置邮件基础信息
    helper.setTo(emailAddress);
    helper.setSubject("你的订单详情邮件");
    helper.setFrom("your-service-email@example.com");
    
    // 4. 准备Velocity模板上下文,传递cid变量
    Map<String, Object> templateModel = new HashMap<>();
    // 这里的cid值要和模板里的cid:${cid}完全匹配
    String imageCid = "orderDetailIcon";
    templateModel.put("cid", imageCid);
    
    // 5. 渲染Velocity模板为HTML内容
    String emailHtmlContent = VelocityEngineUtils.mergeTemplateIntoString(
        velocityEngine,
        "templates/order-mail.vm", // 替换成你的实际模板路径
        "UTF-8",
        templateModel
    );
    helper.setText(emailHtmlContent, true); // 第二个参数设为true,表示发送HTML邮件
    
    // 6. 将图片绑定为内嵌资源,关联cid
    helper.addInline(imageCid, imageResource);
    
    // 7. 发送邮件
    javaMailSender.send(mimeMessage);
}

2. 关键注意事项(必看!)

  • cid严格一致:模板里的cid:${cid}中的cid值,必须和helper.addInline(imageCid, imageResource)的第一个参数完全匹配,大小写也不能错!
  • 文件权限检查:确保你的应用进程有读取/tmp/upload/image/路径的权限(Linux环境下要注意用户权限,比如Tomcat进程是否能访问/tmp目录)。
  • Multipart模式开启:初始化MimeMessageHelper时必须传入true,否则无法处理内嵌资源和HTML邮件。
  • 模板路径配置:确认Velocity引擎能正确找到你的模板文件,比如在Spring配置里指定了模板根目录。

3. 模板代码确认

你已经写的模板代码是正确的,再核对下:

<div> 
  <img src="cid:${cid}" class="iconDetails" /> 
</div>

只要上下文传入的cid和addInline绑定的cid一致,图片就能正常显示在邮件正文中了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:17:37