Node Email Verification Script

In recent tutorial i have explained about sending e-mail using nodemailer package of Node.js. In this tutorial i am going to explain you about e-mail verification system using node.js script which is mandatory thing in sign-up form in order to avoid spam registration. You can integrate this code to any web application which is having user sign up module.

You can download it from Github.

Note : To run the script you have to change two lines in Server.js. You have put your Gmail ID and password in order to send e-mail to any mailbox. Change it once you see the demo.

We are going to use nodemailer to send email’s. To verify e-mail we will generate one random key in our script, store it, and when user click on verification link in e-mail we will fetch the key from that link and compare it to the store one.

rand=Math.floor((Math.random() * 100) + 54);

The above code will generate random number and our job is to store it in temporary variable for further comparison.

So let’s begin with creating package.json file.

package.json
{
  "name": "email-node",
  "version": "1.0.0",
  "dependencies": {
        "nodemailer": "latest",
    "express": "latest"
  }
}

Switch to the project folder (if you don’t have one, create one with any name and paste package.json in it) and type npm install to load all dependencies.

Server script is same as old post ( Send email using Node.js) with one simple difference. i have added one more router (app.get(/verify)) and in that i am verifying information (which is random ID) by clicking to the verification link. Here is a complete code.

Server.js
var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
/*
    Here we are configuring our SMTP Server details.
    STMP is mail server which is responsible for sending and recieving email.
*/

var smtpTransport = nodemailer.createTransport({
    service: "Gmail",
    auth: {
        user: "Your Gmail ID",
        pass: "Gmail Password"
    }
});
var rand,mailOptions,host,link;
/*------------------SMTP Over-----------------------------*/

/*------------------Routing Started ------------------------*/

app.get('/',function(req,res){
    res.sendfile('index.html');
});
app.get('/send',function(req,res){
        rand=Math.floor((Math.random() * 100) + 54);
    host=req.get('host');
    link="http://"+req.get('host')+"/verify?id="+rand;
    mailOptions={
        to : req.query.to,
        subject : "Please confirm your Email account",
        html : "Hello,<br> Please Click on the link to verify your email.<br><a href="+link+">Click here to verify</a>"
    }
    console.log(mailOptions);
    smtpTransport.sendMail(mailOptions, function(error, response){
     if(error){
            console.log(error);
        res.end("error");
     }else{
            console.log("Message sent: " + response.message);
        res.end("sent");
         }
});
});

app.get('/verify',function(req,res){
console.log(req.protocol+":/"+req.get('host'));
if((req.protocol+"://"+req.get('host'))==("http://"+host))
{
    console.log("Domain is matched. Information is from Authentic email");
    if(req.query.id==rand)
    {
        console.log("email is verified");
        res.end("<h1>Email "+mailOptions.to+" is been Successfully verified");
    }
    else
    {
        console.log("email is not verified");
        res.end("<h1>Bad Request</h1>");
    }
}
else
{
    res.end("<h1>Request is from unknown source");
}
});

/*--------------------Routing Over----------------------------*/

app.listen(3000,function(){
    console.log("Express Started on Port 3000");
});

Let me explain you the code. In app.get(‘/verify’) router. First we are determining whether the URL from which ‘/verify’ is invoked is valid or not. Those validation include comparing Host name from where the email is been send, and the host name determine by this router as well as whether it is HTTP or not.

Once domain is authorize, we are comparing our store ID (rand) with ID fetched from URL (req.query.id). If they match then only we can say that account is verified and source of e-mail is valid.

We are using HTML and jQuery for front-end application and here is HTML code which have used as index.html.

index.html
<html>
<head>
<title>Node.JS Email application</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){     
        to=$("#to").val();     
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("<p>Email is been sent at "+to+" . Please check inbox !</p>");
        }

});
    });
});
</script>
<style>
#container
{
    margin-left:400px;
    margin-top:50px;
}
#to,#subject,#content
{
    font-family: "Segoe UI";
    font-size:18px;
    width:530px;
}
h1
{
    font-family: "Segoe UI";
    font-size:40px;
    color: #3b5998;
}
p
{
    color:green;
}
#send_email
{
    font-size:15px;
    font-family: "Segoe UI";
}
#message
{
    font-size:18px;
}
</style>
</head>
<body>
<div id="container">
<h1>Email-verification System in Node.js</h1>
<input type="text" id="to" placeholder="Enter E-mail which you want to verify"><br>
<button id="send_email">Send Email</button><br>
<span id="message"></span>
</div>
</body>
</html>

When user click on Send button, we are calling Node Server using complete URL (http://localhost:3000/send) and in “/send” router we dealt with sending e-mail. I hope this is useful to you.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 126