使用SendGrid发送电子邮件的DRY代码

时间:2015-01-18 15:29:18

标签: javascript node.js express sendgrid

我在帖子路线中有这个代码:

第一个是在用户在我的网站注册时提醒我:

sendgrid.send({
        to:         "my@email.com",
        from:       "myother@email.com",
        subject:    "[ALERT] " + req.body.eventDate,
        html:       "SOME HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        } 
        else {
            next();
        }
});

下一个是发送给新注册会员的确认电子邮件:

sendgrid.send({
        to:         req.body.email,
        from:       "my@email.com",
        subject:    "[CONFIRM] register" + req.body.eventDate,
        html:       "SOME HTML",
    },
    function(err, json) {
        if (err) {
            return console.error(err);
        } 
        else {
            next();
        }
});

100%工作,但这不是一个好习惯,有太多重复。我可以干吗?如果是这样,怎么样?

感谢!!!

1 个答案:

答案 0 :(得分:2)

您可以使用sendgrid创建一个可以执行发送电子邮件操作的功能,

function sendEmail(options) {
  sendgrid.send(options,
    function(err, json) {
        if (err) {
            return console.error(err);
        } 
        else {
            next();
        }
  });
}

然后你可以使用以上创建的函数,

用于发送注册电子邮件

var registrationEmailOptions = {
        to:         "my@email.com",
        from:       "myother@email.com",
        subject:    "[ALERT] " + req.body.eventDate,
        html:       "SOME HTML",
}
sendEmail(registrationEmailOptions);

用于发送确认电子邮件。

var confirmationEmailOptions = {
        to:         req.body.email,
        from:       "my@email.com",
        subject:    "[CONFIRM] register" + req.body.eventDate,
        html:       "SOME HTML",
}
sendEmail(confirmationEmailOptions);