Home > DeveloperSection > Beginner > How to Send Mail in Node.JS

How to Send Mail in Node.JS


Node.JS JavaScript  Node JS 
Ratings:
0 Comment(s)
 2675  View(s)
Rate this:

How to Send Mail in Node.JS

In this article, I’m explaining the concept of how to send email in node.js. In this article we create a simple mail transfer example that send mail message to requested mail. This article is related to express project.

 

In this article, I’ creating a simple program in node.js express. In this article we know that how to send email  in node.js. There are following steps to create the project to send email:

 

Step 1 Create an express project

 

First of all create an express as previous created. First open up the command prompt and select your location where you want to create it.

Hit enter and create a project whose named as SendMail.

 

Step 2 Remove Unused Items

 

Here, remove all unused item that is not used. First open your project and remove the bin, public, routes, views and also app.js file remove all things from your project because I’ m not used all these things. So it remove it. Let’s see that:

 

By do this easy learn how nodemailer work and not to complicated.

Step 3 Install Dependency

 

Now open the package.json file from the folder and write this code code simply:

 

{

  "name": "email-node",

  "version": "1.0.0",

  "dependencies": {

    "nodemailer": "~0.7.1",

    "express": "~4.5.1"

  }

}

In this there only two package first is express and second one is nodemailer.Express give the necessary facility for the project and nodemailer is the module that give the facility to send mail from node.js.

Now install the all packages. Now simply run the npm install:

 

Hit enter from the keyboard it install in few seconds. Let’s move on create user interface.

 

 

Step 4 Add User Interface to Send Mail

 

Now need to create the user interface to send the mail. It’s create by simple html file in the project.

Create an index.html file in the project for it:

 

 

This is created by the following code:

<html>

<head>

<title>Node.JS Send Email Application</title>

<style>

#container

{

                margin-left:400px;

                margin-top:50px;

}

.text-style

{

                font-family: "Times New Roman";

                font-size:18px;

                width:400px;

}

h1

{

                font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;

                color: darkblue;

}

.success

{

                color: green;     

}

.error

{

                color: red;

}

.button-style

{

                color: rgb(245, 245, 245);

                background-color: rgb(34, 80, 226);

                height: 45px;

                width: 130px;

                border-radius: 5px;

                font-weight: bold;

 

}

.message-style

{

                font-family: "Monotype Corsiva";

                font-size:18px;

}

.label-text

{

                font-weight: bold;

                font-size:18px;

}

 

</style>

</head>

<body>

<div id="container">

<h1>Send Mail in Node.JS</h1>

<div class="label-text"><label>To</label><div><input type="text" id="to" class="text-style" placeholder="Email where you want to send" value=""></div><br>

<label class="label-text">Subject</label></label><div><input type="text" id="subject" class="text-style" placeholder="Subject" value=""></div><br>

<label class="label-text">Message</label></label><div><textarea id="content" rows="5" cols="40" class="text-style" placeholder="Message" value=""></textarea></div><br>

<button id="send_email" class="button-style">Send Email</button><br>

<span id="message" class="message-style"></span>

<span id="success" class="success"></p>

<span id="error" class="error"></p>

</div>

</body>

</html>

By this create a user interface. Let’s move on the coding part.

 

Step 5 Create a Mail file

 

Now create the mail which send the email as Mail.js in the project. Let’s add a file Mail.js then add code:

 

Here add the necessary module for the program.

/*

Add Modules for express and email

*/

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 receiving email.

 

// Configure the SMTP server with service gmail and user name and password

var smtpTransport = nodemailer.createTransport("SMTP",{

    service: "Gmail",

    auth: {

        user: "yuoremail@gmail.com",

        pass: "youremailpassword"

    }

});

 

 

Here create route for the index page that render at the browser

// Routing Started

app.get('/',function(req,res){

                res.sendfile('index.html');

});

app.get('/send',function(req,res){

                var mailOptions={

                                to : req.query.to,

                                subject : req.query.subject,

                                text : req.query.text

                }

                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");

                 }

});

});

 

After that finaly add the which port start appication

// Start at port 3000

app.listen(3000,function(){

                console.log("Server start at port: 3000");

});

 

Step 6 Need to Add JQuery and Show Message

 

Here need to add JQuery in application. If you need to download then http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js from this or you connected with internet then add as script tag in the index.html file.

This line add the JQuery to use its functions.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

 

Now add some code to access the functionality of email get the success or failed message by this code.

<script>

$(document).ready(function(){

                var from,to,subject,text;

                $("#send_email").click(function(){

                                $("#error").text('');       

                                $("#message").text('');

                                $("#success").text('');

                                to=$("#to").val();

                                subject=$("#subject").val();

                                text=$("#content").val();

                                if($('#to').val() == "" || $('#subject').val() == "" || $('#content').val() == "")

                                {

                                                alert("Please fill all textbox");

                                                $('#to').focus();

                                                return false;

                                }

                                else

                                {

                                $("#message").text("Sending E-mail...Please wait");

                                $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){

                                if(data=="sent")

                                {

                                                $("#success").text("Email has been sent successfully. Please check inbox !");

                                }

                                else

                                {

 

                                                $("#error").text("Sending Email is Failed !");

                                }

 

 

});

}

                });

});

</script>

Now you are ready to run it with some validation.

 

Step 7 Run Application

 

Now run application from the command prompt by the node Mail.js then run on the browser at http://localhost:3000//. Let’s see it:

 

Let’s test it by giving the blank fields. It give the error message:

Let’s now wrong email id that not send and the error message:

 

Let’s send an email successfully:

 

 

Yah! It’s working. Send Mail successfully.

I hope that this article is very helpful for you! Thanks!


Don't want to miss updates? Please click the below button!

Follow MindStick