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

Node.js使用SendGrid发送PDF附件报错,寻求解决方案

解决SendGrid发送PDF附件时的「Invalid type」错误

这个错误的核心原因很清晰:fs.readFile默认返回的是Buffer对象,而SendGrid的attachments.content字段要求传入的是base64编码的字符串,不是原始的Buffer,所以才触发了类型不匹配的报错。

下面给你几种可行的解决方案:

方案1:读取文件时直接指定base64编码

调用fs.readFile时把第二个参数设为'base64',这样读取到的data本身就是符合要求的字符串:

sgMail.setApiKey(my_key);
fs.readFile('pdf/4.pdf', 'base64', function(err, data) {
  // 先处理文件读取错误
  if (err) {
    console.error('读取PDF文件失败:', err);
    return;
  }

  sgMail.send({
    to: 'dinesh@mail.com',
    from: 'xxxxxxxxx@jdk.com',
    subject: 'Report',
    attachments: [{
      filename: 'Report.pdf',
      content: data,
      type: 'application/pdf',
      disposition: 'attachment' // 明确标记为附件,部分邮箱客户端需要这个字段
    }],
    html: 'bla bla'
  })
  .then(() => console.log('邮件发送成功'))
  .catch(sendErr => console.error('邮件发送失败:', sendErr));
});

方案2:将Buffer转换为base64字符串

如果不想修改读取文件的方式,也可以用Buffer的toString('base64')方法把二进制数据转成符合要求的字符串:

sgMail.setApiKey(my_key);
fs.readFile('pdf/4.pdf', function(err, data) {
  if (err) {
    console.error('读取PDF文件失败:', err);
    return;
  }

  sgMail.send({
    to: 'dinesh@mail.com',
    from: 'xxxxxxxxx@jdk.com',
    subject: 'Report',
    attachments: [{
      filename: 'Report.pdf',
      content: data.toString('base64'), // 关键:转成base64字符串
      type: 'application/pdf',
      disposition: 'attachment'
    }],
    html: 'bla bla'
  })
  .then(() => console.log('邮件发送成功'))
  .catch(sendErr => console.error('邮件发送失败:', sendErr));
});

方案3:用async/await简化代码(推荐)

如果你的代码运行在支持async/await的Node.js环境中,可以用Promise版的fs.promises.readFile让代码更简洁易读:

async function sendReportEmail() {
  try {
    sgMail.setApiKey(my_key);
    // 读取文件并直接获取base64字符串
    const pdfData = await fs.promises.readFile('pdf/4.pdf', 'base64');
    
    await sgMail.send({
      to: 'dinesh@mail.com',
      from: 'xxxxxxxxx@jdk.com',
      subject: 'Report',
      attachments: [{
        filename: 'Report.pdf',
        content: pdfData,
        type: 'application/pdf',
        disposition: 'attachment'
      }],
      html: 'bla bla'
    });

    console.log('邮件发送成功');
  } catch (err) {
    console.error('操作失败:', err);
  }
}

// 调用函数发送邮件
sendReportEmail();

额外注意事项

  • 一定要处理文件读取和邮件发送过程中的错误,避免程序因为异常崩溃
  • 添加disposition: 'attachment'字段可以确保所有邮箱客户端都正确识别这是附件,避免出现显示异常的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:04:03