如何在nodejs和SendGrid发送电子邮件确认?



我有一个NodeJs和ReactJs项目,其中用户可以注册在用户注册后,他们会收到一封电子邮件来确认他们的帐户。

所以现在当我注册电子邮件工作得很好。但它适用于我这样设置的电子邮件。

function sendMail() {
const msg = {
to: "someoneemail@gmail.com", 
from: "myemail@gmail.com", 
subject: "a subject",
text: "some text herer",
html: "<strong>and easy to do anywhere, even with Node.js</strong>",
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
}
module.exports = { sendMail };

我需要删除这个to: "someoneemail@gmail.com"*

  1. ,而不是设置用户的电子邮件,用户注册在此系统

  2. 而不是text:,我必须发送令牌.

所以这是注册部分:

router.post("/register", async (req, res) => {
const { fullName, emailAddress, password } = req.body;
const user = await Users.findOne({
where: {
[Op.and]: [{ fullName: fullName }, { emailAddress: emailAddress }],
},
});
if (user) {
res.status(400).send({
error: `some message.`,
});
} else {
bcrypt
.hash(password, 10)
.then((hash) => {
return {
fullName: fullName,
emailAddress: emailAddress,
password: hash,
isVerified: false,
};
})
.then((user) => {
const token = TokenGenerator.generate();
const creator = Verifications.belongsTo(Users, { as: "user" });
return Verifications.create(
{
token,
user: user,
},
{
include: [creator],
}
);
})
.then((verification) => {
console.log("verification", verification);
sendMail();
})
.then(() => res.json("User, Successmessage "));
}
});

但是代码不在同一个文件中

只需将您需要的参数添加到sendMail函数:

function sendMail(user, token) {
const msg = {
to: user.emailAddress, 
from: "myemail@gmail.com", 
subject: "Sending with SendGrid is Fun",
text: token,
html: `<strong>${token}</strong>`,
};
sgMail
.send(msg)
.then(() => {
console.log("Email sent");
})
.catch((error) => {
console.error(error);
});
}

还要在承诺中注入所需的参数:

.then(async (user) => {
const token = TokenGenerator.generate();
const creator = Verifications.belongsTo(Users, { as: "user" });
await Verifications.create(
{
token,
user: user,
},
{
include: [creator],
}
);
return {user, token};
})
.then(({user, token}) => {
sendMail(user, token);
})
.then(() => res.json("User, Successmessage "));

最新更新