繁体   English   中英

node.js Nodemailer 对象数组到 CSV 文件作为 email 中的附件

[英]node.js Nodemailer array of objects to CSV file as attachment in email

我正在使用 nodemailer 模块在 node.js 中发送 email。 我有一组对象,我试图将其转换为 CSV 文件并将其附加到 email。我能够成功发送 email,但 CSV 附件未正确填充(显示为空白)。 我的代码类似于以下内容

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);
});

我猜它无法读取对象数组并且只适用于以逗号分隔的字符串?

您应该将附加content属性指定为字符串。

NodeMailer本身无法转换格式。 因此,您需要先将数据转换为CSV,然后再发送。 使用类似to-csv的模块。

您可以创建对象数组或 arrays 的数组并使用convert-array-to-csv将其转换为 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
        }],
       };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM