meabhisingh / mernProjectEcommerce

This is MERN Stack Ecommerce Project Made to Teach MERN Stack on YouTube
1.15k stars 828 forks source link

Forgot Password Verification (Postman) #50

Closed HetMamtora closed 1 year ago

HetMamtora commented 1 year ago

image I need a help with this error. POP & IMAP is enabled on the email that I am using with this forgot password verification but I'm not able to send mail through smtp.

sendEmail.js const nodeMailer = require("nodemailer");

const sendEmail = async (options)=>{

const transporter = nodeMailer.createTransport({
    service: process.env.SMPT_SERVICE,
    auth: {
        user: process.env.SMPT_MAIL,
        pass: process.env.SMPT_PASSWORD,
    },
});

const mailOptions = {
    from: process.env.SMPT_MAIL,
    to: options.email,
    subject: options.subject,
    text: options.message,
  };

await transporter.sendMail(mailOptions);

};

module.exports = sendEmail;

userController.js //FORGOT PASSWORD exports.forgotPassword = catchAsyncErrors(async (req, res, next) => { const user = await User.findOne({ email: req.body.email });

if (!user) {
  return next(new ErrorHander("User not found", 404));
}

// Get ResetPassword Token
const resetToken = user.getResetPasswordToken();

await user.save({ validateBeforeSave: false });

const resetPasswordUrl = `${req.protocol}://${req.get(
  "host"
)}/password/reset/${resetToken}`;

const message = `Your password reset token is :- \n\n ${resetPasswordUrl} \n\nIf you have not requested this email then, please ignore it.`;

try {
  await sendEmail({
    email: user.email,
    subject: `Ecommerce Password Recovery`,
    message,
  });

  res.status(200).json({
    success: true,
    message: `Email sent to ${user.email} successfully`,
  });
} catch (error) {
  user.resetPasswordToken = undefined;
  user.resetPasswordExpire = undefined;

  await user.save({ validateBeforeSave: false });

  return next(new ErrorHander(error.message, 500));
}

});

config.env SMPT_SERVICE="gmail" SMPT_MAIL="tempmailabc@gmail.com" SMPT_PASSWORD="password"