How to attach a node.js readable stream to a Sendgrid email?

限于喜欢 提交于 2019-12-10 20:25:59

问题


I'm using PDFKit to generate PDFs. I'm using Nodejitsu for hosting, so I can't save the PDFs to file, but I can save them to a readable stream. I'd like to attach that stream in a Sendgrid email, like so:

sendgrid.send({
    to: email,
    files: [{ filename: 'File.pdf', content: /* what to put here? */ }]
    /* ... */
});

I've tried doc.output() to no avail.


回答1:


To use the SendGrid nodejs API with a streaming file, just convert the streaming into a buffer. You can convert a readable stream into a buffer using stream-to-array.

var streamToArray = require('stream-to-array');

streamToArray(your_stream, function (err, arr) {
  var buffer = Buffer.concat(arr)
  sendgrid.send({
    to: email,
    files: [{ filename: 'File.pdf' content: buffer }]
  })
})



回答2:


I recently struggled with this issue myself, and I just wanted to share what worked for me:

//PdfKit

var doc = new PDFDocument({
    size: 'letter'
});
doc.text('My awesome text');
doc.end();


//Sendgrid API

var email = new sendgrid.Email();

    email.addTo         ('XXX@gmail.com');
    email.setFrom       ('XXX@gmail.com');
    email.setSubject    ('Report');
    email.setText       ('Check out this awesome pdf');
    email.addFile       ({
            filename: project.name + '.pdf',
            content: doc,
            contentType: 'application/pdf'
        });

sendgrid.send(email, function(err, json){
    if(err) {return console.error(err);}
    console.log(json);
});

The key is to make "doc" the content in your file attachment



来源:https://stackoverflow.com/questions/23896270/how-to-attach-a-node-js-readable-stream-to-a-sendgrid-email

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