node.js sendgrid how to attach a pdf

試著忘記壹切 提交于 2019-11-30 15:55:18

According to the README, you should just pass your content, not turn it into a data URI.

fs.readFile('public_html/img/Report.pdf', function(err, data) {
    sendgrid.send({
        to        : hexDecode(_.e),
        from      : 'xxxxxxxxx@gmail.com',
        subject   : 'Report',

        files     : [{filename: 'Report.pdf', content: data}],
        html      : 'bla bla'

With the latest version of the library, it goes like:

fs.readFile('public_html/img/Report.pdf', function(err, data) {
    sendgrid.send({
        to          : hexDecode(_.e),
        from        : 'xxxxxxxxx@gmail.com',
        subject     : 'Report',
        attachments : [{filename: 'Report.pdf', 
                       content: data
                       type: 'application/pdf',
                       disposition: 'attachment',
                       contentId: 'myId'
        }],
        html        : 'bla bla'

The field is called "attachments" now.(https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md#attachments).

Quite weird, I haven't really checked the docs and such because of answers beforehand already did but this was how I did mine and it worked.

function base64_encode(file){
var 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",

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!