margherita pizza
margherita pizza

Reputation: 7185

sendgrid attach a pdf file in node js

Hi I am trying to send a pdf attachment with an email.

sgMail.setApiKey(my_key);
        fs.readFile('pdf/4.pdf', function(err, data) {

            sgMail.send({
                to          : '[email protected]',
                from        : '[email protected]',
                subject     : 'Report',
                attachments : [{filename: 'Report.pdf', 
                               content: data,
                               type: 'application/pdf',
                }],
                html        : 'bla bla'})})

This code gives me an error

 Invalid type. Expected: string, given: object.

But I found this code snippet by another stackoverflow answer. It says you don't need to pass the uri encoded data for the content. (That question in the comments)

How do I achieve this using node js?

Upvotes: 2

Views: 3293

Answers (1)

zai
zai

Reputation: 131

I did encode mine to base64 and this is how I did it. Maybe this helps.

function base64_encode(file){
  let bitmap = fs.readFileSync(file);
  return new Buffer(bitmap).toString('base64');
}

let data_base64 = base64_encode('../invoice.pdf');

const msg = {
to: emails,
from: '-----.com',
subject: `Invoice`,
text: `Invoice`,
html: "whatever",
attachments: [
  {
    filename: `invoice`,
    content: data_base64,
    type: 'application/pdf',
    disposition: 'attachment'
  }
 ]
};

sgMail
.send(msg)
.then((response) => {
  res.status(200).send('Success');
})
.catch((err) => {
  res.status(500).send(err);
});

hope this helps other people. using @sendgrid/mail": "^6.3.1",

Upvotes: 7

Related Questions