【问题标题】:Can't properly attach pdf made with nodejs PDFKit to email sent through Nodemailer无法将使用 nodejs PDFKit 制作的 pdf 正确附加到通过 Nodemailer 发送的电子邮件中
【发布时间】:2016-06-16 23:33:49
【问题描述】:

我在将使用 pdfkit(node) 制作的 pdf 附加到通过 nodemailer 和 Sendgrid API 发送的电子邮件时遇到问题。电子邮件工作正常。生成到磁盘的 pdf 文件很好,但附件中的 pdf 文件不断损坏且无法读取。我尝试了许多不同的变体,并通过谷歌进行了研究,但我不确定如何让它发挥作用。

创建 pdf 的代码:

var fs = require('fs');
var PDFDocument = require('pdfkit');

doc = new PDFDocument({
    size: 'letter'
});

doc.pipe(fs.createWriteStream('./public/img/test.pdf'));

doc.text('my text')

doc.end();

我的 nodemailer 代码:

var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');
var options = {
    auth: {
        api_key: process.env.SENDGRID_API
    }
}
var mailer = nodemailer.createTransport(sgTransport(options));

var email = {
        to: 'XXXXXXXX@gmail.com',
        from: 'example@gmail.com',
        subject: 'Please work',
        text: 'Check out this pdf',
        attachments: [{
            filename: 'test.pdf',
            path: './public/img/test.pdf',
            contentType: 'application/pdf'
        }]
    };

mailer.sendMail(email, function(err, res){
    if (err){
        console.log(err);
    }
    console.log(res);
});

我错过了什么吗?我没有将 pdf 写入磁盘,而是读到另一种方法是将 pdf 直接流式传输到我的电子邮件。除了我也不知道该怎么做。

【问题讨论】:

    标签: node.js email pdf nodemailer node-pdfkit


    【解决方案1】:

    我也遇到了同样的问题。我注意到我在邮箱中收到的文件缺少最后几行,导致文件损坏。

    原因是文件系统fs没有时间写完邮件已经用Nodemailer发送的pdf。

    您需要等待fs 写入流上的“完成”事件。这就是我所做的:

      const doc = new PDFDocument();
      const fileName = 'aPdfFile.pdf';
      const writeStream = fs.createWriteStream(fileName);
      doc.pipe(writeStream);
    
      // do something with your pdf document ...
    
      doc.end();
      writeStream.on('finish', function () {
        // call the callback function or in my case resolve the Promise.
        resolve(fileName);
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-19
      • 1970-01-01
      • 2017-05-16
      • 2014-11-11
      • 1970-01-01
      • 2017-02-08
      相关资源
      最近更新 更多