how to use nodemailer in nodejs for bulk data sending?

我是研究僧i 提交于 2021-02-11 06:08:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!