Mrugesh
Mrugesh

Reputation: 4517

How to send pdf file as an attachment in sendgrid node.js v3 client

I am using v3 node.js client to send an email. Now , I want to send pdf attachment with the email. I went through the API documentation. But I did not find anywhere how to do it.

I am using the following code to send an email.

const msg = {
        to: process.env.EMAIL_ID,
        from: process.env.ALERT_EMAIL_ID,
        subject: subjectText,
        text: info
    };

    sgMail.send(msg);

Upvotes: 3

Views: 2076

Answers (1)

Saras Arya
Saras Arya

Reputation: 3112

Let us assume your PDF is in S3.

Get your file from S3

const pdfFile = await s3
       .getObject({
         Bucket: PDF_BUCKET_NAME,
         Key: `flight-${fileName}.pdf`,
       })
       .promise();

Once you have the file

const base64data = pdfFile.Body.toString('base64');

const data = {
        from: '[email protected]',
        to: user.emailId,
        subject: 'Your ticket for flight PNR XYSSA1 from DEL-BLR',
        html: `Please find attached your ticket
            <br><br>Regards<br>
            Team Example`,
        attachments: [
          { content: base64data, filename: 'flight-ticket', type: 'application/pdf', disposition: 'attachment' },
        ],
      };

await sgMail.send(data);

In case you have your file in the filesystem, just get the buffer from fs.readFile convert it into base64 like shown above and repeat the steps and you should be good to go.

Upvotes: 1

Related Questions