首页 > 解决方案 > Sendgrid Node.js 错误:将循环结构转换为 JSON

问题描述

我正在使用 Sendgrid 使用 Nodejs 通过 Firebase Cloud Functions 发送交易电子邮件。

const attachment = file.createReadStream();

const msg = {
  to: email,
  from: "test@test.com",
  subject: "print order",
  templateId: "templateid",
  dynamic_template_data: {
    dashboardurl: `/order#${orderId}`,
    downloadurl: orderData.downloadurl
  },
  attachments: [{
    content: attachment,
    filename: "order.pdf",
    type: "application/pdf",
    disposition: "attachment"
  }]
};
await sgMail.send(msg);

由于以下错误,电子邮件不会发送:

TypeError: Converting circular structure to JSON

Firebase 存储解决方案

const tempFilePath = path.join(os.tmpdir(), "tmp.pdf");
await file.download({ destination: tempFilePath });
const attachment = fs.readFileSync(tempFilePath, { encoding: "base64"   });

标签: node.jsfirebasegoogle-cloud-functionssendgridsendgrid-templates

解决方案


根据文档

对于内容,您发送文件的 base64 编码版本。

const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
  to: 'recipient@example.org',
  from: 'sender@example.org',
  subject: 'Hello attachment',
  html: '<p>Here’s an attachment for you!</p>',
  attachments: [
    {
      content: 'Some base 64 encoded attachment content',
      filename: 'some-attachment.txt',
      type: 'plain/text',
      disposition: 'attachment',
      contentId: 'mytext'
    },
  ],
};

因此,在您的情况下,以下转换就足够了:

const attachment = fs.readFileSync('filepath', { encoding: 'base64' });

推荐阅读