问题
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