Search code examples
node.jsfirebasegoogle-cloud-functionssendgridsendgrid-templates

Sendgrid Node.js Error: Converting circular structure to JSON


I'm using Sendgrid to send a transactional Email with Firebase Cloud Functions using Nodejs.

const attachment = file.createReadStream();

const msg = {
  to: email,
  from: "[email protected]",
  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);

The Email won't send, because of the following bug:

TypeError: Converting circular structure to JSON

Solution for Firebase Storage

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

Solution

  • According to doc:

    For content you send base64 encoded version of the file.

    const sgMail = require('@sendgrid/mail');
    sgMail.setApiKey(process.env.SENDGRID_API_KEY);
    const msg = {
      to: '[email protected]',
      from: '[email protected]',
      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'
        },
      ],
    };
    

    So in your case below conversion would suffice:

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