[英]DRY code for sending email with SendGrid
I have this code inside a post route: 我在发布路由中包含以下代码:
The first one is to alert my when a user register in my site: 第一个是当用户在我的网站中注册时提醒我:
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();
}
});
The next one is a confirmation email send to the new register member: 下一封是发送给新注册会员的确认电子邮件:
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();
}
});
Is working 100%, but this is not a good practice, there is so much duplicate. 正在100%工作,但这不是一个好习惯,有太多重复项。 Can i DRY this? 我可以烘干吗? If so, howww?? 如果是这样,怎么?
Thanks!!! 谢谢!!!
You can create a function which can perform the operation of sending emails using sendgrid
like this, 您可以创建一个函数来执行使用sendgrid
这样发送电子邮件的操作,
function sendEmail(options) {
sendgrid.send(options,
function(err, json) {
if (err) {
return console.error(err);
}
else {
next();
}
});
}
And then you can utilise above created function as following, 然后,您可以利用上面创建的函数,如下所示:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.