Node.js SendGrid 如何附加 PDF

Ben*_*oft 3 pdf email-attachments node.js sendgrid

我正在使用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'
Run Code Online (Sandbox Code Playgroud)

有谁知道如何防止“无法加载pdf文档”??

Roc*_*que 5

使用最新版本的库,它是这样的:

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'
Run Code Online (Sandbox Code Playgroud)

该字段现在称为“附件”。(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);
});
Run Code Online (Sandbox Code Playgroud)

希望这对其他人有帮助。使用@sendgrid/mail": "^6.3.1",


Ry-*_*Ry- 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'
Run Code Online (Sandbox Code Playgroud)