Sending a PDF created dynamically as an attachment using PDFKit in a nodejs application

試著忘記壹切 提交于 2019-12-07 04:02:28

A pdfkit instance is a stream, which you can simply pass to nodemailer:

const doc = new pdfkit();

transport.sendMail({
  from: '...',
  to: '...',
  subject: '...',
  text: '...',
  attachments: [{
    filename: 'attachment.pdf',
    content: doc,
  }],
});

Don't use BlobStream. Write to buffers instead as suggested here: how to convert pdfkit object into buffer using nodejs

let pdf = new pdfkit();

let buffers = [];
pdf.on('data', buffers.push.bind(buffers));
pdf.on('end', () => {

    let pdfData = Buffer.concat(buffers);

    const mailOptions = {
        from: '..',
        to: "...",
        attachments: [{
            filename: 'attachment.pdf',
            content: pdfData
        }]
    };

    mailOptions.subject = 'PDF in mail';
    mailOptions.text = 'PDF attached;
    return mailTransport.sendMail(mailOptions).then(() => {
        console.log('email sent:');
    }).catch(error => {
        console.error('There was an error while sending the email:', error);
    });

});

pdf.text('Hello', 100, 100);
pdf.end();

I used this approach and was able to use nodemailer with buffer Attachmend and send a correct pdf.

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