Node.js SendGrid如何附加PDF

7
我正在使用SendGrid在我的Node.js应用程序中发送电子邮件。无论我尝试哪种组合来附加pdf,最终附加的pdf都无法阅读。
我已经尝试过:
fs.readFile('public_html/img/Report.pdf',function(err,data){
    var base64data = new Buffer(data).toString('base64');

    sendgrid.send({
        to        : hexDecode(_.e),
        from      : 'xxxxxxxxx@gmail.com',
        subject   : 'Report',
        
        files      : [{filename:'Report.pdf',content:'data:application/pdf;base64,'+base64data}],
        // files   : [{filename:'Report.pdf',contentType:'data:application/pdf',url:'public_html/img/'Report.pdf'}],
        // files   : [{filename:'Report.pdf',url:'public_html/img/'Report.pdf'}],
        html       : 'bla bla'

有人知道如何防止“无法加载PDF文档”吗?

3个回答

7

使用最新版本的库,操作如下:

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'

现在该字段称作“attachments”。(参见https://github.com/sendgrid/sendgrid-nodejs/blob/master/packages/mail/USE_CASES.md#attachments).

5

这很奇怪,我之前已经看了几个答案,没有查看文档等其他信息,但是我按照自己的方式操作,它奏效了。

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

希望这能帮助其他人。 使用的是"@sendgrid/mail": "^6.3.1"。


3
根据README的说明,您只需传递内容,而不需要将其转换为数据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'

1
它只发送文件的16kb数据,其余部分保持不变。 - Dharmendra Pratap Singh
1
@DharmendraPratapSingh 我们能为此做些什么? - margherita pizza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接