Nodemailer send base64 data URI as attachment. How?

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


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

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

var pixel = "data:image/gif;base64,"
    + "R0lGODlhAQABAIABAP///wAAACH5"
    + "BAEKAAEALAAAAAABAAEAAAICTAEAOw==";
var buffer = new Buffer(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 = new Buffer(pixel.split("base64,")[1], "base64");

You can simply use the package nodemailer-base64-to-s3.

Install the package:

npm install -s nodemailer-base64-to-s3

Configure it with nodemailer:

var base64ToS3 = require('nodemailer-base64-to-s3');
var nodemailer = require('nodemailer');

var transport = nodemailer.createTransport({});
transport.use('compile', base64ToS3(opts));

https://github.com/ladjs/nodemailer-base64-to-s3