所以我创建了mern stack电子商务应用程序,使用nodejs作为服务器。我尝试使用nodemailer和gmail作为主机向新用户发送确认电子邮件。我尝试启用两步验证并生成密码,因为我应该,但我仍然没有收到任何电子邮件,也收到标题中写的错误。有人可以帮忙吗?
我创建的包含发送电子邮件功能的类:
import nodemailer from 'nodemailer';
export const sendEmail=async(subject,message,send_to,send_from,reply_to)=>{
var transporter=nodemailer.createTransport({
service:process.env.EMAIL_SERVICE,
auth:{
user:process.env.EMAIL_USER,
pass:process.env.EMAIL_PASS
},
tls:{
rejectUnauthorized:false,
}
});
const options={
from:send_from,
to:send_to,
replyTo:reply_to,
subject,
html:message,
}
transporter.sendMail(options,function(err,info){
if(err){
console.log(err)
}
else{
console.log(info)
}
})
}
export default sendEmail;
报名路线:
export const register=catchAsync(async(req,res,next)=>{
const{fullName,email,password,confirmPassword,type,Wishlist}=req.body;
if(!fullName||!email||!password||!confirmPassword||!type){
return next(new ErrorHandling("One or more of the fields is empty",400));
}
if(password!=confirmPassword){
return next(new ErrorHandling("Password fields does not equal",400));
}
if(!validateEmail(email)){
return next(new ErrorHandling("The email you entered is illegal",400));
}
if(await User.findOne({email})){
return next(new ErrorHandling("Email already exists",400));
}
try{
await sendEmail('Consumer account confirmation',`<h3>Welcome to Base herbal cosmetics</h3><p>Thank you for your registration</p><button>press here to join</button>`,process.env.EMAIL_USER,email,email)
}catch(err){
return next(new ErrorHandling(err.message,err.statusCode));
}
const newUser=await User.create({
fullName,
email,
password,
confirmPassword,
type,
Wishlist
})
res.status(201).json({
status:"success",
data:{
newUser
}
})
});
值得一提的是,用户确实添加到了我的数据库中,除了电子邮件之外的所有内容都工作正常。
从您的 Google 帐户设置中,单击“安全”选项卡,转到两步验证并启用它(没关系,因为它已经启用了)。 现在,在两步验证下,向下滚动到应用程序密码,生成一个唯一的密码,并在代码中使用它,而不是登录电子邮件时使用的传统密码。
出现这种情况的原因是 Google 的安全性。传统登录时,输入密码后还有一步验证;但由于 NodeMailer 仅使用一个密码阶段,这就是为什么 Google 为那些可能想要以编程方式访问其帐户的人提供了该选项。