1

我正在建立一个网站联系表。我通过 Angular js 将表单提交添加到 Firebase。当向 Firebase 提交新的提交时,我在 Node 中使用 child_added 来触发 nodemailer。这工作正常,除了每当我重新启动开发服务器时都会重新通过电子邮件发送整个提交集合,并且每天在 Heroku 上的生产中多次发送。如何确保电子邮件不会被多次发送?

var myRoot = new Firebase('https://firebase.firebaseio.com/website/submissions');

myRoot.on('child_added', function(snapshot) {
    var userData = snapshot.val();
    var smtpTransport = nodemailer.createTransport("SMTP",{
        auth: {
            user: "email@gmail.com",
            pass: "password"
        }
    });

var mailOptions = {
    from: "Website <email@gmail.com>", // sender address
    to: "email@email.com.au", // list of receivers
    subject: "New  Website Lead", // Subject line
    html: "<p><strong>Name: </strong>" + userData.name + "</p>" + "<p><strong>Email: </strong>" + userData.email + "</p>" + "<p><strong>Phone: </strong>" + userData.phone + "</p>" + "<p><strong>Enquiry: </strong>" + userData.enquiry + "</p>" + "<p><strong>Submitted: </strong>" + userData.date + "</p>" // html body
};

smtpTransport.sendMail(mailOptions, function(error, response) {
    if(error) {
        console.log(error);
    }
    else {
        console.log("Message sent: " + response.message);
    }
    smtpTransport.close();
    });
});
4

2 回答 2

1

为此目的,该'child_added'事件可能不是一个好的选择。该事件并不意味着一个孩子刚刚被新添加到 Firebase 中的某个集合中;当您有子对象时,它会触发从 Firebase加载的每个子对象,此外还会在新添加子对象时触发。ref因此,每次加载该集合时(例如,当您重新启动服务器时)您的邮件程序都会为每个加载的子项调用(因此重复)。

当添加新提交时,您最好发送传统的 http 请求以从您的角度操作触发邮件程序。

I suppose you could add a field indicating whether or not the child has already been mailed, and only mail children that haven't been on a 'child_added' event. But this seems inelegant to me.

于 2013-11-01T02:34:47.327 回答
1

Every time a child is added, move the child to a different branch of your firebase (or simply delete the child if you don't need a record of the event).

on('child_added', function(oldSnap) {
    eventHistoryRef.push(oldSnap.val());
    oldSnap.ref().remove();
    // use nodemailer
});
于 2013-11-01T07:52:25.240 回答