5

I'm sending an email in node.js using nodemailer module. I have an array of objects that I'm trying to turn into a CSV file and attach it to the email. I am able to successfully send an email, but the CSV attachment doesn't populate correctly (showing up as blank). My code looks similar to the following

var nodemailer = require('nodemailer');

// create reusable transporter object using SMTP transport
    var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {
        user: 'gmail.user@gmail.com',
        pass: 'userpass'
     }
});

var data = [{age:24,name:"bob"},{age:35,name:"andy"},...];

var mailOptions = {
    from: 'foo@blurdybloop.com', // sender address
    to: 'bar@blurdybloop.com', //receiver
    subject: 'Hello', // Subject line
    text: 'Hello world', // plaintext body
    html: '<b>Hello world</b>', // html body
    attachments: [{   
        filename: 'test.csv',
        content: data 
    }],
};

// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
    if(error){
        return console.log(error);
    }
    console.log('Message sent: ' + info.response);
});

I'm guessing it's not able to read the array of objects and only works for a string separated by commas?

Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35

2 Answers2

6

You should to specify attach content property as a string.

NodeMailer couldn't convert formats itself. So you need to convert data into CSV before sending it. Use module like to-csv.

Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35
3

You can create an array of objects, or an array of arrays and use convert-array-to-csv to convert it to csv

   const {convertArrayToCSV} = require('convert-array-to-csv');

    var data = [{age:24,name:"bob"},{age:35,name:"andy"},...];

    //Array of objects so dont need to pass the header (age, name)
    const csvData = convertArrayToCSV(data);

    //In case you have array of arrays
    data= [[24,'bob'],[35,'andy']]
    header= ['age','name']

    const csvData = convertArrayToCSV(data, {
       header,
       separator: ',' 
     });


   var mailOptions = {
       from: 'foo@blurdybloop.com', 
       to: 'bar@blurdybloop.com', 
       subject: 'Hello', 
       text: 'Hello world', 
       html: '<b>Hello world</b>', 
       attachments: [{   
          filename: 'test.csv',
          content: csvData   // attaching csv in the content
        }],
       };
Biswambar
  • 65
  • 2
  • 8