Sendgrid-nodejs: Base64 encoded PDF as attachment

Created on 15 Apr 2016  ·  4Comments  ·  Source: sendgrid/sendgrid-nodejs

I have a PDF file base64 encoded and want to attach it to an email. When I attach it with the following code, the email sent has a corrupt PDF attached:

email.addFile({
    filename: 'my-file.pdf',
    content: aBase64EncodedPDF,
    contentType: 'application/pdf',
}); 

Most helpful comment

You will have added a base64 string as an attachment with the above code, which means you would need to save the attachment and decode it at the other end. I think you may have really wanted to do this:

email.addFile({
    filename: 'my-file.pdf',
    content: new Buffer(aBase64EncodedPDF, 'base64'),
    contentType: 'application/pdf',
}); 

All 4 comments

You will have added a base64 string as an attachment with the above code, which means you would need to save the attachment and decode it at the other end. I think you may have really wanted to do this:

email.addFile({
    filename: 'my-file.pdf',
    content: new Buffer(aBase64EncodedPDF, 'base64'),
    contentType: 'application/pdf',
}); 

@deaks-kt thanks for your contribution!

@danielflippance did that solve your issue?

Thanks for the info. Would that solution double the amount of memory being used? IE: I'd now have a base64 string and a buffer containing the same information. If so, that would significantly increase the memory use on our servers as the PDFs are quite large, so would not be appropriate in our case. I'll look into whether we can retrieve a buffer before rendering to base64.

I suspect it will be close to double. You get 3 bytes for every 4 of Base64, which is a 25% reduction, but I expect there will be some overhead for the Array. If you are really stuck and must use the base64, then I'd recommend investigating pull request #219 and looking at https://github.com/form-data/form-data (which is what this library is using via request) to see if you can either stream the base64 decode or maybe even specify that the form data is already encoded during in the form.append

Was this page helpful?
0 / 5 - 0 ratings