Email existence check using nodejs

In the previous article, we saw how to verify mobile number using Nodejs. Now in this article, we will perform Email existence check using nodejs. This article will be helpful in order to avoid invalid emails added into our database.

For example, let's say you have a Blog Subscription Field and you want to check whether given email from user exists or not. Now you can do this by 2 ways, first By sending verification Email and second by using this method Which we will implement now.

1. How it works:

Here we perform Email existence check using nodejs and kickbox API. Kickbox offers Email existence check by actually not sending an email to users email address.

Kickbox verifies email addresses using the Simple Mail Transfer Protocol (SMTP). You can get more insight about how kickbox API works visit this link.

2. Signing up with Kickbox Account

Go to this link create an account. You can perform first 100 Email existence check using nodejs , PHP, Python and Ruby for free, after that they will charge you.

At the left side, you should see the navigation panel Click on verify API. You should see below image.

Email existence check using nodejs kickbox verification apiKickbox Verify API

2.1 Creating a new Verification app and getting API KEY :

Create a new app on clicking  new app button and give it a name. For example am naming it as codershood.

Email existence check using nodejs kickbox verification api create new app

 Create a new Kickbox Application

After creating your application, you can see the stats and usage of your application. Below you will find your API KEY keep this safe, however, you can regenerate it. We will use this key in our Nodejs Project.

Email existence check using nodejs kickbox verification app stats and usage

Stats,Usage and API key

3. Email existence check using nodejs

3.1 Creating new Nodejs project:

In this application, we will give the option to enter Email and we will hit kickbox API to verify the same. Below in our Project folder structure.

Project folder Structure :

+--- utils
|    +-- config.js
|    +-- helper.js
|    +---routes.js
|
+--- node_modules
|    \ body-parser
|      \ ejs
|      \ express
|    \ kickbox
|
+--- public_data
|	\ css
|		|
|		+-- bootstrap.min.css	
|		+-- style.css	
|	\ js
|		|
|		+-- angular.min.js	
|		+-- script.js 
|
+---- views
|    	|
|       +-- index.html
|
+---server.js
+---package.json

To create a new project run npm init command. This command will create a package.json file, below is our package.json file.

package.json:

{
  "name": "email-existence-check",
  "version": "0.0.1",
  "description": "Email existence check using Nodejs",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Shashank Tiwari",
  "license": "MIT",
  "dependencies": {
    "body-parser": "^1.15.0",
    "ejs": "^2.4.2",
    "express": "^4.13.4",
    "kickbox": "^2.0.0"
  }
}

 

3.2 creating config file:

1. Create a folder named as utils inside root directory this folder contains files which take care of our routes and configuration.

2. Create a file named as config.js inside utils folder. This file will take of express related configuration.
config.js:

var express = require("express");
var path= require('path'); 
 
var method=config.prototype;

function config(app){
    
    // Setting .html as the default template extension
	app.set('view engine', 'html');

	// Initializing the ejs template engine
	app.engine('html', require('ejs').renderFile);

	// Telling express where it can find the templates
	app.set('views', (__dirname + '/../views'));

	//Files 
	app.use(express.static(path.join('public_data')));
	
}

method.get_config=function(){
	return this;
}

module.exports = config;

3. Now create a file called  server.js.
server.js:

/*requiring node modules starts */
var app = require("express")();
var http = require('http').Server(app);
/*requiring node modules ends */

/* requiring config file starts*/
var config =require('./utils/config.js')(app);
/* requiring config file ends*/

require('./utils/routes.js')(app);


http.listen(81,function(){
    console.log("Listening on http://127.0.0.1:81");
});

4. Now create a file named as helper.js inside utils folder. This holds the function which is used to hit KICKBOX API.
helper.js:

'use strict';
const API_KEY = "KICKJBOX_API_KEY";
const TIMEOUT = 6000; 
const kickbox = require('kickbox').client(API_KEY).kickbox();

const self={
    verifyEmail : function(data,callback){

    	kickbox.verify( data.email, {timeout: TIMEOUT },function (err, response) {
			callback(response.body);
		});	
	}
}
module.exports = self;

5. Creating routes.js file to handle routes for our application. In below code we have  /verifyEmail route to verify Email.

In this route, we are first checking whether given email is valid or not if an email is valid then we are calling KICKBOX API by using a helper function.

routes.js:

'use strict';
const bodyParser = require('body-parser');
const helper = require('./helper');
const regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

var method=routes.prototype;
function routes(app){
    
    app.use(bodyParser.json());
	
	app.get('/', function(req, res){
		res.render('index');
	});
	
	app.post('/verifyEmail', function(req, res){

		const email = req.body.email;
		response = {};

		if(! regEx.test(email)){
			response.process = false;
			response.message = "Enter valid Email.";
		}else{

			const data ={
				email : email
			};

			helper.verifyEmail( data, function(result){
				res.writeHead(200, {'Content-Type': 'text/plain'});
				res.end(JSON.stringify(result));
				res.end();
			});
		}
	});
}

method.getroutes=function(){
	return this;
}

module.exports = routes;

3.3 Creating FrontEnd Files:

1. Now our NodeJs server  is ready, It's time to create  Front End Files. Here I will use AngularJS for client side. We don't have to do too much work for client side. For this application, we have only one textbox with one button. Below is code for index.html.

index.html:

<html ng-app="home">
<head>
    <title>Email existence check using nodejs : Codershood.info</title>
    <link rel="stylesheet" href="css/bootstrap.min.css">
	<link rel="stylesheet" href="css/style.css">
</head>
<body ng-controller="index">
	<div class="container"> 
		<div class="sendEmailContainer">
			<h3>Verify your Email:</h3>
				<input type = "email" name="email" class = "form-control" 
						ng-model="email"/>
				<br/>					
				<button class="btn btn-primary" placeholder="Enter Email address" 
						ng-click="verifyEmail()" 
						ng-class="( disabled == true ? 'disabled' :'')">
					verify Email
				</button>
		</div>
	</div>

	<script type="text/javascript" src = "js/angular.min.js"></script>
	<script type="text/javascript" src ="js/script.js"></script>

  </body>
</html>

2. Let's  create AngularJS script to make our HTML useful. In below code we are making an Ajax request to the server with user's email ID.
script.js:

'use strict';
const app = angular.module('home',[]);

/*---------------------------------------------------------------------------------
    Making service to run ajax Start
---------------------------------------------------------------------------------*/
app.service('runAjax', ['$http', function ($http) {
    this.runAjaxFunction = function(request,callback){

        const url = request.url;
        const data = request.data;
        const headers = request.headers;

        $http.post(url,data,headers).success(function(data, status, headers, config) {
            callback(data);
        })
        .error(function(err){
            callback(err);
        });
    }
}]);
/*---------------------------------------------------------------------------------
    Making service to run ajax End
---------------------------------------------------------------------------------*/

app.controller('index', function ($scope,runAjax) {

    $scope.disabled = false;
    var regEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    $scope.verifyEmail = function(){

        $scope.disabled = true;

        if(! regEx.test($scope.email)){

            alert(`Enter valid Email`);
        }else{

            const Data={
                url:'/verifyEmail',
                data : {
                    email :$scope.email
                }
            }

            /* Calling runAjax Service*/

            runAjax.runAjaxFunction(Data,function(response){
                alert(`Your Email address is `+ response.result);
                $scope.disabled = false;
            });
        }
    }
});

One important note:
This API is rate-limited to a maximum of 25 simultaneous connections per account.  When you integrate this Kickbox API in your application, make sure your application does not exceed this limit.

I hope you liked this article Give your comment feedback and suggestion in below comment box. I would love to hear them.