Search code examples
node.jsnodemailer

Nodemailer send base64 data URI as attachment. How?


Basically I have an image created using Canvas and it's in base64 encoded data URI. This data URI is then attached to email.

...,
 attachments:[{
 filename: "cat.jpg",
 contents: new Buffer(cat, 'base64')
}],

The email is received but the attachment is not viewable. Running $ file cat.jpg in linux returns:

cat.jpg: ASCII text, with very long lines, with no line terminators

Why is this ASCII? I had already mentioned base64. How may I fix this problem? Thank you.


Solution

  • The variable cat probably includes the 'data:image/jpeg;base64,' part. You shouldn't pass that bit to Buffer.from.

    It seems that if you pass in invalid data, Buffer.from() doesn't complain:

    var pixel = "data:image/gif;base64,"
        + "R0lGODlhAQABAIABAP///wAAACH5"
        + "BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
    var buffer = Buffer.from(pixel, "base64"); // does not throw an error.
    

    You even get back a valid Buffer. The buffer is a corrupt image (or rather, it doesn't begin with an image header).

    You have to strip the first part of the data URI yourself:

    var buffer = Buffer.from(pixel.split("base64,")[1], "base64");
    

    Edit (may 2021): Changed new Buffer to Buffer.from, as the former is deprecated.