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

在Express.js中如何在EJS邮件模板嵌入图片?附报错咨询

解决Nodemailer中"attachments is not defined"错误及EJS模板传递CID的问题

1. 修复"attachments is not defined"错误

你的代码核心问题是把attachments配置放错了位置——attachments是邮件发送时的选项,不属于transporter的初始化配置项。正确的做法是将attachments数组从nodemailer.createTransport()的参数中,移到transporter.sendMail()的参数对象里。

2. 向EJS模板传递CID值

要在EJS中引用内嵌图片的CID,只需在渲染模板时把CID作为数据字段传入,再在模板里通过模板语法调用:

  • 调用ejs.renderFile()时,将CID添加到数据对象;
  • 在EJS模板中,用<img src="cid:<%= cid %>">的格式引用内嵌图片。

修改后的完整代码

const nodemailer = require("nodemailer");
const path = require("path");
const ejs = require("ejs");
sendMail = async (req, res) => {
  console.log("controller");
  // 初始化transporter,此处无需attachments配置
  let transporter = nodemailer.createTransport({
    service: "gmail",
    auth: {
      user: "tanjibrubyat@gmail.com",
      pass: "qaaqcvbjgnyrhgrr",
    },
  });
  
  const type = req.body.type;
  const text = req.body.text;
  const name = req.body.name;
  const student_id = req.body.student_id;
  const lead_id = req.body.lead_id;
  // 统一定义CID,方便维护
  const imageCid = "unique@nodemailer.com";
  let info;
  let file = path.join(__dirname, "../../../views/skilled.ejs");

  // 渲染EJS时传入CID
  const data = await ejs.renderFile(file, {
    text,
    type,
    name,
    student_id,
    lead_id,
    cid: imageCid // 传递CID到模板
  });
    
  const recipient = [req.body.to];
  for (let i = 0; i < recipient.length; i++) {
    info = await transporter.sendMail({
      from: "tanjibrubyat@gmail.com",
      to: recipient[i],
      subject: req.body.subject,
      html: data,
      // 将attachments移到sendMail的参数中
      attachments: [
        {
          filename: "image.png",
          path: path.join(__dirname, "../../../public/images/b2cde6d6-a2fa-439a-b06f-1bf93360760f.jpg"), // 用path.join避免相对路径问题
          cid: imageCid,
        },
      ],
    });
  }
};

EJS模板示例(skilled.ejs)

<!-- 其他模板内容 -->
<img src="cid:<%= cid %>" alt="Logo">
<!-- 其他模板内容 -->

额外提示:建议用path.join()拼接图片路径,避免不同运行环境下的相对路径失效问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:46