我在下面有 nodemailer 代码,它很好并且可以工作。我的问题是将个人数据发送到个人电子邮件。id_array 有两封电子邮件,而 no_array 有两个单独的数据,我如何将“1”发送到[email protected] 并将“2”发送到[email protected]?
var id_array = ["[email protected]","[email protected]"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: "[email protected]",
pass: "mypassword"
}
});
var mail = {
from: "Sachin Murali <[email protected]>",
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();
});
在循环中为每个接收者准备参数,并使用 promise 并行运行所有电子邮件
var id_array = ["[email protected]","[email protected]"];
var no_array = ["1","2"];
var mailer = require("nodemailer");
// Use Smtp Protocol to send Email
var smtpTransport = mailer.createTransport({
service: "Gmail",
auth: {
user: "[email protected]",
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 <[email protected]>",
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();
});
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句