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

DRY code for sending email with SendGrid

我在 post 路由中有这段代码:

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

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% 工作,但这不是一个好的做法,有太多重复项。我可以擦干这个吗?如果是这样,howww??

谢谢!!!

您可以创建一个函数来执行使用 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);