Zee Oct
Zee Oct

Reputation: 21

how to solve email sending issue " Internal Server Error " using nodeMailer in node js

I want to send a confirmation email using nodemailer, but in production it says internet server error when I allow insecure apps for Gmail accounts, even though it works locally.

How can I fix this?

router.post("/forgotPass", (req, res, next)=>{
    async.waterfall([
    function(done){
    crypto.randomBytes(20, (err, buf)=>{
        var token = buf.toString('hex');
         done(err, token);
            })
        },
        function(token, done){
         user.findOne({email : req.body.email}, (err, user)=>{
                if(!user){
                    req.flash("error", "No account with this email address exists!");
                    console.log("now account with this email exists !")
                   return   res.redirect("back");
                }
                user.resetPasswordToken = token;
                user.resetPasswordDuration = Date.now() + 3600000; //1 hour

                user.save((err)=>{
                    done(err, token, user);
                    console.log("the error is " + err);
                });
            })
        },
        function(token, user, done){
            var smtpTransport = nodeMailer.createTransport({
                service : 'Gmail',
                auth:{
                    user:'[email protected]',
                    pass : process.env.GMAIL_PW
                }
            });
            var mailOptions = {
                to : user.email,
                from : '[email protected]',
                subject : 'passwor Reset!',
                text : "you are receiving this email because you want to reset you password in mY App ." + 
                "please click the link below to complete the process. " +
                "http://" + req.headers.host + "/resetPass/" + token + "\n\n" +
                "if you did not request this, please ignore this email and your password will be untouched." 
            };
            smtpTransport.sendMail(mailOptions, (err)=>{
                console.log('mail sent!');
                req.flash("success", "an email has sent to " + user.email + " with further instructions");
                done(err, 'done');
            });
        }
    ], function(err){
        if(err){
            return next(err);
        } res.redirect("/forgotPass");
    });
});

Upvotes: 2

Views: 205

Answers (1)

advaiyalad
advaiyalad

Reputation: 163

You will need to enable less secure app access for your account - Google does not allow you to use your account through a program without that enabled. However, you can enable 2-factor auth in GMail and use an app password as your password.

Upvotes: 1

Related Questions