Sendgrid Node.js Ошибка: преобразование круговой структуры в JSON - PullRequest
0 голосов
/ 24 марта 2020

Я использую Sendgrid для отправки транзакционного электронного письма с функциями Firebase Cloud, используя Nodejs.

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"   });

1 Ответ

1 голос
/ 24 марта 2020

Согласно do c:

Для содержимого вы отправляете версию файла в кодировке 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' });
...