【问题标题】:sendgrid attach a pdf file in node jssendgrid 在节点 js 中附加一个 pdf 文件
【发布时间】:2019-02-27 12:37:08
【问题描述】:

您好,我正在尝试通过电子邮件发送 pdf 附件。

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

            sgMail.send({
                to          : 'dinesh@mail.com',
                from        : 'xxxxxxxxx@jdk.com',
                subject     : 'Report',
                attachments : [{filename: 'Report.pdf', 
                               content: data,
                               type: 'application/pdf',
                }],
                html        : 'bla bla'})})

这段代码给了我一个错误

 Invalid type. Expected: string, given: object.

但我在另一个 stackoverflow 答案中找到了这段代码 sn-p。它说您不需要为内容传递 uri 编码数据。 (cmets中的那个问题)

如何使用 node js 实现这一点?

【问题讨论】:

标签: node.js sendgrid


【解决方案1】:

我确实将我的编码为 base64,我就是这样做的。也许这会有所帮助。

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

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

【讨论】:

  • new Buffer(bitmap).toString('base64') 已弃用,请改用 Buffer.from(bitmap).toString('base64')
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-07-14
  • 1970-01-01
  • 2019-12-07
  • 2014-03-20
  • 2016-08-09
  • 2019-07-19
  • 1970-01-01
相关资源
最近更新 更多