You need to enable JavaScript to run this app. Node.js下Google Cloud Storage远程文件转Base64对接SendGrid邮件API
优惠活动
大模型
产品
解决方案
定价
更多

Node.js下Google Cloud Storage远程文件转Base64对接SendGrid邮件API

Google Cloud Storage PDF 转 Base64 适配 SendGrid 附件实现

实现逻辑

通过GCS Node.js客户端的文件下载接口将远程PDF内容拉取为内存Buffer,再利用Buffer原生方法转换为Base64字符串,最终按照SendGrid的附件规范组装参数即可直接使用。

完整代码示例

基于你已有的初始化逻辑补充后续处理代码:

const { Storage } = require("@google-cloud/storage");
const storage = new Storage(options);
const bucket = storage.bucket(bucketName);   
let remoteFile = bucket.file(fileName);

// 拉取PDF并生成符合SendGrid要求的附件对象
async function buildSendGridPdfAttachment() {
  try {
    // 无destination参数时,download方法会返回[文件Buffer, 接口响应对象]
    const [pdfBuffer] = await remoteFile.download();
    // 转换为Base64字符串
    const base64Pdf = pdfBuffer.toString("base64");

    // 严格按照SendGrid附件字段要求组装
    return {
      content: base64Pdf,
      filename: fileName,
      type: "application/pdf",
      disposition: "attachment"
    };
  } catch (err) {
    // 可在此处统一处理权限不足、文件不存在等异常
    console.error("PDF转附件失败:", err);
    throw err;
  }
}

// 调用示例:拿到附件对象后直接传入SendGrid邮件请求的attachments数组即可
buildSendGridPdfAttachment().then(attachment => {
  // 此处替换为你实际的SendGrid请求逻辑
  console.log("可直接使用的附件参数:", attachment);
});

注意事项

  • 无需为转Base64临时写入本地文件,直接使用download()返回的Buffer可减少IO开销,同时避免临时文件清理遗漏的问题。
  • 若PDF体积超过10MB,可调整download()的分块读取参数,或改用remoteFile.createReadStream()结合流处理方式转Base64,避免内存占用过高。
  • 必须显式指定附件type为application/pdf,否则部分邮件客户端可能无法正确识别文件格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 13:06:03