Nodemailer send base64 data URI as attachment. How?

Ильич Ленин picture Ильич Ленин · Jun 11, 2014 · Viewed 7.3k times · Source

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.

Answer

lohsie picture lohsie · Feb 3, 2016

A buffer is not needed. You can just put the string starting from behind the base64 encoding prefix into it:

var cat = "...base64 encoded image...";
var mailOptions = {
  ...
  attachments: [
    {   // encoded string as an attachment
      filename: 'cat.jpg',
      content: cat.split("base64,")[1],
      encoding: 'base64'
    }
  ]
};

More Details you find here: https://github.com/nodemailer/nodemailer#attachments