今天要接著完成:
一樣在昨天的forgotPassword controller中
建立一組重置密碼的url&要寄給使用者的訊息
const resetUrl = `${req.protocol}://${req.get('host')}/api/v1/auth/resetPassword/${resetToken}`;
const message = `You are receiving this email because you has requested the reset of a password. Please make a PUT request to: ${resetUrl}`;
resetToken指的是昨天隨機生成的那串代碼(未加密過)
接著在utils資料夾建立sendEmail.js
copy&paste Nodemailer的sample code XD
const sendEmail = async (options) => {
const transporter = nodemailer.createTransport({
host: SMTP_HOST,
port: SMTP_PORT,
auth: {
user: SMTP_EMAIL,
pass: SMTP_PASSWORD
}
});
const message = {
from: `${FROM_NAME} <${FROM_EMAIL}>`,
to: options.email,
subject: options.subject,
text: options.message
};
const info = await transporter.sendMail(message);
}
transporter中host, port, auth的值須從Mailtrap SMTP Settings複製過來
message的from, to, text指的是寄件人&收件人的資訊, 以及信件的內容
回到forgotPassword controller
try {
await sendEmail({
email: user.email,
subject: 'Password reset token',
message
});
res.status(200).json({
success: true,
data: 'Email sent'
});
} catch(err) {
user.resetPasswordToken = undefined;
user.resetPasswordExpire = undefined;
await user.save({ validateBeforeSave: false });
return next(new ErrorResponse('Email could not be sent', 500));
}
email寄送成功的畫面: