将node.js对象对象的Nodemailer数组转换为CSV文件作为电子邮件中的附件 [英] node.js Nodemailer array of objects to CSV file as attachment in email
问题描述
我正在使用nodemailer模块在node.js中发送电子邮件。我有一系列对象,试图将其转换为CSV文件并将其附加到电子邮件中。我能够成功发送电子邮件,但是CSV附件无法正确填充(显示为空白)。我的代码类似于以下内容
var nodemailer = require(’nodemailer’);
//使用SMTP传输
创建可重复使用的传输器对象var transporter = nodemailer.createTransport({
service:'Gmail',
auth:{
用户:'gmail.user@gmail.com',
密码:'userpass'
}
});
var data = [{age:24,name: bob},{age:35,name: andy},...];
var mailOptions = {
从:'foo@blurdybloop.com',//发件人地址
到:'bar@blurdybloop.com',//收件人
subject:'Hello',//主题行
text:'Hello world',//纯文本主体
html:'< b> Hello world< / b>',// html body
附件:[{{
文件名:'test.csv',
内容:数据
}],
};
//使用定义的传输对象发送邮件
transporter.sendMail(mailOptions,function(error,info){
if(error){
return console.log (错误);
}
console.log('消息发送:'+ info.response);
});
我猜它无法读取对象数组,只能用于由逗号?
您应将Attach content
属性指定为字符串。 / p>
NodeMailer本身无法转换格式。因此,您需要先将数据转换为CSV,然后再发送。使用类似 to-csv 的模块。
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?
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.
这篇关于将node.js对象对象的Nodemailer数组转换为CSV文件作为电子邮件中的附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!