问题
i have nodemailer code below, its fine and working.My problem is to send individual data to individual email. id_array have two emails and no_array have two individual data, How do i send "1" to prayag@cybrosys.in and "2" to 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:
Prepare the parameters for each receiver in a loop and use a promise to run all emails in parallel
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();
});
})
}
来源:https://stackoverflow.com/questions/55860585/how-to-use-nodemailer-in-nodejs-for-bulk-data-sending