如何在nodejs中使用nodemailer进行批量数据发送?
Posted
技术标签:
【中文标题】如何在nodejs中使用nodemailer进行批量数据发送?【英文标题】:how to use nodemailer in nodejs for bulk data sending? 【发布时间】:2019-09-15 13:16:31 【问题描述】:我在下面有 nodemailer 代码,它很好并且可以工作。我的问题是将个人数据发送到个人电子邮件。 id_array 有两封电子邮件,no_array 有两个单独的数据,我如何将“1”发送到prayag@cybrosys.in,将“2”发送到 blockchain@cybrosys.net?
var id_array = ["prayag@cybrosys.in","blockchain@cybrosys.net"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport(
service: "Gmail",
auth:
user: "mymail@gmail.com",
pass: "mypassword"
);
var mail =
from: "Sachin Murali <blockchain@cybrosys.net>",
to: [id_array],
subject: "Sachin's Test on new Node.js project",
text: [no_array]
// html: "<b>"\"[no_array]\""</b>"
smtpTransport.sendMail(mail, function(error, response)
if(error)
console.log(error);
else
console.log("Message sent: " + JSON.stringify(response));
smtpTransport.close();
);
【问题讨论】:
【参考方案1】:在循环中为每个接收者准备参数,并使用 Promise 并行运行所有电子邮件
var id_array = ["prayag@cybrosys.in","blockchain@cybrosys.net"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport(
service: "Gmail",
auth:
user: "mymail@gmail.com",
pass: "mypassword"
);
let emailPromiseArray = [];
//prepare the email for each receiver
for(let i=0;i<id_array.length;i++)
emailPromiseArray.push(
sendMail(
from: "Sachin Murali <blockchain@cybrosys.net>",
to: id_array[i],
subject: "Sachin's Test on new Node.js project",
text:no_array[i]
)
)
//run the promise
Promise.all(emailPromiseArray).then((result)=>
console.log('all mail completed');
).catch((error)=>
console.log(error);
)
function sendMail(mail)
return new Promise((resolve,reject)=>
smtpTransport.sendMail(mail, function(error, response)
if(error)
console.log(error);
reject(error);
else
console.log("Message sent: " + JSON.stringify(response));
resolve(response);
smtpTransport.close();
);
)
【讨论】:
当我运行上面的代码时出现错误:“sendmail is not defined” 我的意思是检查函数名是否正确,你说""sendmail 未定义" 但在我的代码中M
是大写
当我复制你的代码时出现错误:ReferenceError: smtpTransport is not defined以上是关于如何在nodejs中使用nodemailer进行批量数据发送?的主要内容,如果未能解决你的问题,请参考以下文章
Nodejs 学习笔记 - 使用 nodemailer 发送邮件