【问题标题】:node.js sending mails with a delaynode.js 延迟发送邮件
【发布时间】:2016-07-14 14:51:22
【问题描述】:

我正在做一件简单的事情,但它不起作用。

我想做的是延迟 30 秒发送邮件。

代码如下:

user.forEach(function(data) {


    var locals = {
        fname: data.Name,
        your_name: data.From,

    }

    template.render(locals, function(err, results) {

        if (err) {
            return console.error(err)
        } else {
            transporter.sendMail({

                to: data.Email,
                subject: "Welcome",
                replyTo: data.ReplyTo,
                html: results.html,
                text: results.text,
            }, function(error, info) {
                console.log("here");
                if (error) {
                    console.log(error);
                } else {
                    console.log('Message sent: ' + info.response);
                };

            });
        }

    });
});

这里的用户是一个对象数组,其中包含电子邮件、发件人、姓名等详细信息。

数组中的每个对象都有要发送的特定邮件的详细信息。

我想发送一封邮件并等待 30 秒,然后发送第二封邮件……然后等待,依此类推。

我使用了 setInterval 和 npm sleep,但这不起作用。它会等待 30 秒,然后一次发送所有邮件。

【问题讨论】:

    标签: javascript node.js email


    【解决方案1】:

    您应该将同步 forEach 替换为异步实现。
    Option1.使用 async.js eachLimit 并以 30 秒的延迟调用回调
    Option2. 您可以为您的发送电子邮件功能编写包装器,例如:

    var emails = ['email1', 'email2' /*...*/];
    function sendEmailAndWait(email, callback){
        // your stuff
        transporter.sendMail(email, function(error, info) {
            // handle results
            if(!emails.length) return callback();
            setTimeout(function () {
                sendEmailAndWait(emails.shift(), callback);
            }, 30*1000)
        })
    }
    sendEmailAndWait(emails.shift(), function(){  /* allDone */});
    

    【讨论】:

    • 如果达到调用堆栈限制,递归函数将失败。想象一下队列中有 5000 封电子邮件。
    【解决方案2】:
     setTimeout(function() {
      template.render(locals, function(err, results) {
    
        if (err) {
            return console.error(err)
        } else {
            transporter.sendMail({
    
                to: data.Email,
                subject: "Welcome",
                replyTo: data.ReplyTo,
                html: results.html,
                text: results.text,
            }, function(error, info) {
                console.log("here");
                if (error) {
                    console.log(error);
                } else {
                    console.log('Message sent: ' + info.response);
                };
            });
        }
    });
     }, 3000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 2012-06-26
      • 2018-01-17
      • 2010-10-08
      • 2011-07-01
      • 1970-01-01
      相关资源
      最近更新 更多