Signup with email verification using Mailgun SMTP, bcrypt & nodemailer in MEAN Stack

Signup with email verification using Mailgun SMTP, bcrypt & nodemailer in MEAN Stack.

I want to share my knowledge for nodejs beginner.

Here you will learn about sending mail using nodemailer SMTP setting using mailgun.

Bcrypt for encrypting password using async process.


Steps are as -

1- First need to install some packages to accomplish the task

- npm install bcrypt --save

- npm install nodemailer --save

note: “--save” is used to add dependency in your package.json

2- Setup your mailgun domain here





Here is example code. Please read comments to understand code.


var express = require('express');
var app = express();
var mongoose = require('mongoose');
var bcrypt = require('bcrypt');
var model = require('../models/adminModel');
var bodyParser = require('body-parser');

var nodemailer = require("nodemailer");
var transporter = nodemailer.createTransport({
host: 'smtp.mailgun.org',
port: 587,
secure: false, // true for 465, false for other ports
auth: {
user: 'Put Your Login email from mailgun smtp setting', // generated ethereal user
pass: 'put your password got from mailgun smtp settings' // generated ethereal password
}
});



module.exports = function(app){

   app.use(bodyParser.json());
   app.use(bodyParser.urlencoded({ extended: true }));


   // HERE I am getting the post data for saving user.
   app.post('/saveuser', function(req, resp, next){


        //capturing posted data in post variable
          post = req.body;
        //using bcrypt generating salt first.
        //saltRounds is a number I am using it 12 for making it more secure


          bcrypt.genSalt(saltRounds, function(err, salt) {
              // hashing your password using generating salt
              bcrypt.hash(post.password, salt, function(err, hash) {
              post.password = hash;
              post.is_active = true;
              post.is_verified = false;// setting for is email verified
        // getting admin user schema from model class
              admin = new model.Admin(post);
        // saving user
             admin.save().then(function(user){
                 // after successfully saving data
                 //generating email verification code here in token variable using bcrypt and user email so it should be unique.
                bcrypt.hash(post.email, salt, function(err, token) {
                    // saving verification code with user id in verification schema
                    verifyEmailcode = new model.VerifyCode({user_id: user._id, token: token});
                     // savuing email verification code in mongo database
                     verifyEmailcode.save();
                     // creating a link for verification email and sending it to mail.
                     link="http://"+req.get('host')+"/verify?id="+token;
                    // setting mail option with text
                    var mailOptions = {

                              from: 'From Email<email@youremail.com',
                              to: post.email,
                              subject: 'School Admin Verification Email',
                              html : "Hello "+post.name+",<br> Please Click on the link to verify your email.<br><a href="+link+">Click here to verify</a>"
                            

                        };
                   // sending mail using nodemiler
                   transporter.sendMail(mailOptions, (error, info) => {

                    if (error) {
                        return console.log(error);
                    }
                  });
               });

            resp.send(JSON.stringify({success: true}));

         }).catch(next);
      });
  });

});

// middleware function to capture errors and pass it to your front end.

// for catch next function
app.use(function (err, req, res, next) {

    res.status(422).send({title: err.code, error: {message: err.errmsg}});

});

}



If anything is not clear please comment here. I will add more details accordingly.

Comments

Popular Posts