How to Send e-mail using Node.js

In this tutorial i am going to discuss about sending e-mail with Node.js. I have already covered Express.js tutorials and in this tutorial also i am going to use Express.js and NodeMailer package. In many forums and blogs people used to ask about sending e-mail’s using Node.js for account verification, password recovery and promotion. So let’s begin with tutorial and at the end you will have Node application which is able to send e-mail’s to any one’s account.

Links: Watch live Demo on YouTube here and Download it from Github here.

What we are Building ?

How to send e-mail in node.js

Create package.json file and keep it in any folder. Put the below code in it.

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

Once done. Switch to that folder using Command prompt or Terminal and type npm install. It will download and install the dependencies our project need. After completion you will able to see node_modules folder in your project directory.

Implementing Server.js:

Let’s begin with creation of our Server file. Paste code shown below in file named as “Server.js”.

Server.js
var express=require('express');
var nodemailer = require("nodemailer");
var app=express();
app.listen(3000,function(){
console.log("Express Started on Port 3000");
});

This is basic block of our app. If you run it in Terminal you will see console message. Now let’s add some routing logic to tell our app what is supposed to do when Request comes from browser. Add these code just above the app.listen line.

app.get('/',function(req,res){
res.sendfile('index.html');
});

Now when you try to open your app from browser, it will return the index.html as response. Let me show you basic snippet of HTML code.

index.html
<div id="container">
<div></div>
Node.JS Email application
<div>
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>

Now next thing to do is to call our Server from HTML page when user hit on ‘Send Email’ Button. To do so at client end i am using jQuery. Here is code snippet of jQuery inside HTML page only.

index.html
<script>
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){     
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("

Email is been sent at "
+to+" . Please check inbox!

"
);
        }

});
    });
});
</script>

Notice : At $.get we are calling our app with ‘/send’ as handler so now we have to add router in our Server.js file in order to deal with this request. So let’s add some code to handle this route request. Add these code just below of app.get(‘/’) line. File name : Server.js

Server.js
app.get('/send',function(req,res){
//code to send e-mail.
//Will be shown soon.
});

Adding NodeMailer code:

Okay we are almost there, now we have to handle the Mail system. First of all we have to Define Mail transport System (SMTP) so that from that E-mail box our e-mail will be sent. For ease, you can add your Gmail account and password. Add this code just in Server.js just below the ‘var app=express()’ line.

var smtpTransport = nodemailer.createTransport({
    service: "gmail",
    host: "smtp.gmail.com",
    auth: {
        user: "",
        pass: ""
    }
});

We will use this Object to send e-mail. Our app design is when user click on ‘Send email’ Button then only e-mail should be sent, and we have did that part in “app.get(‘/send’)” router. So in that block only paste the code shown below.

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

In above code we have read GET variables send from HTML page and we have call “sendMail()” function using Transport object we have created above. In case there is any confusion here is a complete Server.js file.

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",
    host: "smtp.gmail.com",
    auth: {
        user: "",
        pass: ""
    }
});
/*------------------SMTP Over-----------------------------*/

/*------------------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");
         }
});
});

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

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

And this is how HTML page looks like with all styles and JS.

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>// <![CDATA[
$(document).ready(function(){
    var from,to,subject,text;
    $("#send_email").click(function(){     
        to=$("#to").val();
        subject=$("#subject").val();
        text=$("#content").val();
        $("#message").text("Sending E-mail...Please wait");
        $.get("http://localhost:3000/send",{to:to,subject:subject,text:text},function(data){
        if(data=="sent")
        {
            $("#message").empty().html("

Email is been sent at "+to+" . Please check inbox!

");
        }

});
    });
});
</script>
</head>
<body>
<div id="container">
<h1>Mailer In Node.JS</h1>
<input id="to" type="text" placeholder="Enter E-mail ID where you want to send" />
<input id="subject" type="text" placeholder="Write Subject" />
<textarea id="content" cols="40" rows="5" placeholder="Write what you want to send"></textarea>
<button id="send_email">Send Email</button>
<span id="message"></span>
</div>
</div>

That’s it for now. If you have any queries do let me know in comments.

Shahid (UnixRoot) Shaikh

Hey there, This is Shahid, an Engineer and Blogger from Bombay. I am also an Author and i wrote a programming book on Sails.js, MVC framework for Node.js.

Related Posts

133 Comments

  1. Hello Shahid,

    This was a beautiful, well written article. Just what I was looking for. However, when I try it out on an AWS server I get this error:

    “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at… This can be fixed by moving the resource to the same domain or enabling CORS.”

    1. Hello Keith,
      This can be solved by installing CORS package using npm and implementing it using documentation. Mainly this error occurs when you are trying to communicate with different servers. (or) simply transfer transfer all the files to single domain

  2. Hello Shahid,

    Please disregard my previous comment. It works now. Seems I just needed to edit this line with…

    “$.get(“http://myserverdomain.com:3000/send”,{to:to,subject:subject,text:text},function(data){

    thanks again for a well written post.

  3. Hello Shahid,

    On my website I’m working on implementing the contact form. I’m trying to modularize my mailer. I put the var smtpTransport in the server.js

    I know my routes are connect because I tell my server to use the routes file. I used your routes code as so:

    // Code for mailer functionality
    app.get(‘/’, function(request, response){
    response.sendfile(‘index.html’);
    });

    app.post(‘/’, function(request, response){
    console.log(“in mail controller”);
    var mailOptions = {
    to: request.body.contact_email,
    subject: request.body.subject,
    text: request.body.message
    }
    console.log(mailOptions);
    smtpTransport.sendMail(mailOptions, function(error, response){
    if (error) {
    console.log(error);
    response.end(“error”);
    } else {
    console.log(“Message sent: ” + response.message);
    response.end(“sent”);
    }
    })
    });

    So i know that the send button is accessing this controller because my console says “in mailer controller”, however my errors are as followed:

    { to: undefined, subject: undefined, text: undefined }
    ReferenceError: smtpTransport is not defined

    I’m pretty sure once I get the smtpTransport defined in my server that it will work, however I thought that because the route file talks to the server js that I should be able to call a global variable defined in my server.js file, but I must be mistaken. Can you lead me in the right direction here?

    Many Thanks!
    I’m also searching google for the answer, but supposed other beginner viewers would find this question helpful as well.

    1. Make sure you define smtpTransport above the routes in server.js and pass it to route file. assuming server.js contains smtpTransport variable and route.js contains router, so when you define route in server like this.

      var route = require(“route”) //point to route.js

      do it like this instead.

      var route = require(“route”)(smtpTransport)

      Give it a shot !

      1. Wonderful! That gave me the right direction to make it work! One last question. Gmail is telling me that I need to choose “Allow” in my settings, to let less secure apps access your Google account. Is there another way to set up my app to meet Google’s security settings? I’ve done a little googling, but can’t seem to find anything yet.

        1. If you use Google apps for your email, then it won’t need such security. They recently updated the security setting and sending free mail via external app is prohibited until you allow them in settings.

  4. How could i send the http request for sending my mail with the appropriate email address as the parameter using http.get/http.post of angular js, Also what would be the code for server.js to receive the email address at server side..

    Plz help

    1. It won’t require much work than i provided above. What all you need to do is use $http variable and /send API with required field to send email. Server code will remain same.

      1. $scope.sendmail = function () {
        var dataToPost = {to: “[email protected]”}; /* PostData*/
        $http.get(“/send”, dataToPost)
        .success(function(serverResponse) {

        console.log(serverResponse);
        }).error(function(serverResponse) {
        console.log(serverResponse);
        });
        };

        this is my client side script to send the email field to server.
        server code is same as yours but it is not sending mail to the email address.

        1. $http.get(/send?to=+dataToPost.to)
          .success(function(serverResponse) {

          console.log(serverResponse);
          }).error(function(serverResponse) {
          console.log(serverResponse);
          });
          };
          1. Sorry Shahid, I forgot to tell you that I am using angularjs and this code above is not valid in angularjs, so it is giving error when run.
            Can you guide me that how can i imlpement in angularjs.

          2. Ok follow this code :

            $scope.sendmail = function () {
            var dataToPost = {to: “ashuanhad@gmail.com}; /* PostData*/
            $http({
                url: "/send",
                method: "GET",
                params: {to: dataToPost.to}
             }).success(function(serverResponse) {
            console.log(serverResponse);
            }).error(function(serverResponse) {
            console.log(serverResponse);
            });
            };
    2. I’d love to see an example of your work working as i am a newbie both to angularJS and JS.
      Basicly i am guessing you’ve put your nodemailer logic in a Service with a dependency to $resource
      Which allowed you to access through controllers your emails function as explained in this article.
      But i am always confused to what goes where, JsFiddle is my best friend if you had some examples.

      Thank you all

  5. Hi Shahid,

    i have pasted my complete control code below for your reference.

    //My controller

    var TripDetailCtrl = function ($scope, $http, )
    {
    $scope.SendMail = function ()
    {
    var dataToPost = { to: “[email protected]”, subject: “Test Mail”, text: “This is just a test mail for testing mailing fuctionality” }; /* PostData*/
    $http({
    url: “/send”,
    method: “GET”,
    params: { to: dataToPost.to, subject: dataToPost.subject,text:dataToPost.text }
    }).success(function (serverResponse)
    {
    console.log(serverResponse);
    }).error(function (serverResponse)
    {
    console.log(serverResponse);
    });
    }
    }
    }

    Rest all server js,package.json files content is same as you suggested.
    I am not getting where exactly problem is..?

  6. Hi Shahid,

    i am getting below error, can u please help..

    GET http://localhost:49438/send?subject=Test+Mail&text=This+is+just+a+test+mail+for+testing+mailing+fuctionality&[email protected] 404 (Not Found)

    i have pasted my Angular code below for your reference.

    //my controller & i have function calling mail code
    var TripDetailCtrl = function ($scope, $http)
    {
    $scope.sendmail= function (request)
    {
    var dataToPost = { to: “[email protected]”, subject: “Test Mail”, text: “This is just a test mail for testing mailing fuctionality” }; /* PostData*/
    $http({
    url: “/send”,
    method: “GET”,
    params: { to: dataToPost.to, subject: dataToPost.subject,text:dataToPost.text }
    }).success(function (serverResponse)
    {
    console.log(serverResponse);
    }).error(function (serverResponse)
    {
    console.log(serverResponse);
    });
    }
    }

    rest server.js, package.json files are same as you suggested. i am confused where problem lies as i am new to both angular and node..

    Please suggest

  7. After carefully following yoursteps, I get this error message
    { [Error: connect ECONNREFUSED]
    code: ‘ECONNREFUSED’,
    errno: ‘ECONNREFUSED’,
    syscall: ‘connect’,
    stage: ‘init’ }

  8. Hi,

    Myself Abhijit from India. Currently I am working on nodejs+MongoDB using mongoose. I am new in this.

    In my current scenario, I have two tables (i)member & (ii)business. Every business can have multiple members. I have a key named business_id in member table for referencing business.
    In my business listing I have to show how many members are associated with each business. So my code is:

    Business.find({},function(err,businesses){
    if(businesses)
    {
    business_exist=1;
    for(var m in businesses)
    {
    var businessdetail;
    var membercount;
    Member.find({“business_id”:businesses[m]._id},function(err,members){
    membercount=members.length;
    console.log(membercount);
    });
    console.log(membercount);
    businessdetail = ({ “id”: businesses[m]._id,’name’: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”no_of_members”:membercount});
    all_businesses.push(businessdetail);
    }
    }
    else
    {
    business_exist=0;
    }
    data[0]=business_exist;
    data[1]=all_businesses;
    res.send(data);
    });

    I am getting value of membercount in console for first console.log (i.e. within member query). But whenever I am trying to get value of membercount outside query it is giving undefined.

    Please give a solution ASAP.

    Thanks in advance.

    1. There are two ways, one to make membercount global and another is assigning this variable to membercount. So code will be.
      var self = this;
      self.membercount;
      Business.find({},function(err,businesses){
      if(businesses)
      {
      business_exist=1;
      for(var m in businesses)
      {
      var businessdetail;
      Member.find({“business_id”:businesses[m]._id},function(err,members){
      self.membercount=members.length;
      console.log(membercount);
      });
      console.log(self.membercount);
      businessdetail = ({ “id”: businesses[m]._id,’name’: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”no_of_members”:membercount});
      all_businesses.push(businessdetail);
      }
      }
      else
      {
      business_exist=0;
      }
      data[0]=business_exist;
      data[1]=all_businesses;
      res.send(data);
      });

      1. router.get(‘/’, function(req, res, next) {
        var all_businesses=[];
        var data=[];
        var business_exist=0;
        var membercount;
        var self = this;
        self.membercount;
        Business.find({},function(err,businesses){
        if(businesses)
        {
        business_exist=1;
        for(var m in businesses)
        {
        var businessdetail;
        Member.find({“business_id”:businesses[m]._id},function(err,members){
        self.membercount=members.length;
        console.log(self.membercount);
        });
        console.log(self.membercount);
        businessdetail = ({ “id”: businesses[m]._id,”name”: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”:self.membercount});
        all_businesses.push(businessdetail);
        }
        }
        else
        {
        business_exist=0;
        }
        data[0]=business_exist;
        data[1]=all_businesses;
        res.send(data);
        });
        });

        This is my whole web service block…I have used as you told to use self but even though I am getting membercount undefined outside member query. Please help.

        Thanks in advance.

        1. Don’t define member count as var. Just self.membercount = 0; And this is happening because async nature of Callback. Do one thing define one boolean variable and do this.

          router.get(/, function(req, res, next) {
          var self = this;
          var all_businesses=[];
          var data=[];
          var business_exist=0;
          self.membercount = 0;
          self.memberflag = false;
          Business.find({},function(err,businesses){
          if(businesses)
          {
          business_exist=1;
          for(var m in businesses)
          {
          var businessdetail;
          Member.find({“business_id”:businesses[m]._id},function(err,members){
          self.membercount=members.length;
          console.log(self.membercount);
          self.memberflag = true;
          });
          if(self.memberflag) {
          console.log(self.membercount);
          }
          businessdetail = ({ “id”: businesses[m]._id,name: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”:self.membercount});
          all_businesses.push(businessdetail);
          }
          }
          else
          {
          business_exist=0;
          }
          data[0]=business_exist;
          data[1]=all_businesses;
          res.send(data);
          });
          });
          1. I have tried with this. But same problem is occurring. I am getting values of membercount with in member query correctly but whenever I am trying to get value of membercount its getting 0(zero) as we defined it as zero outside and also memberflag getting false outside query.

            Can you please tell me what actually occurring here and propose a way to solve this problem.

            Thanks in advance.

          2. Like i told you its happening because of callback nature of Node.js Member.find is executing and while its execution Node.js is executing next statement which is console.log(self.membercount);. What you need to make sure is when members.find finish its execution then update the flag to true and access the console.log(self.membercount);. This way execution will halt until and unless members.find() finish its execution.

  9. Thanks.
    What you are telling is absolutely true. Business query executes before member query execution finish.
    Can you please tell me a way or any reference so that I can halt nodejs execution until it finishes member query execution?

    Thanks in advance.

    1. Ya you can use same flag logic or if it did’t work then put members.find in another function and get the callback from here as a member count. like this.

      function find_member(business,callback(){
      Member.find({“business_id”:businesses[m]._id},function(err,members){
      membercount=members.length;
      callback(membercount);
      });
      });
      1. Thanks.
        I was busy for last some days.Can you please tell me how to call find_member callback function from for loop of below block.
        Business.find({},function(err,businesses){
        if(businesses)
        {
        business_exist=1;
        for(var m in businesses)
        {
        var businessdetail;
        businessdetail = ({ “id”: businesses[m]._id,’name’: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”: businesses[m].total_member});
        all_businesses.push(businessdetail);
        }
        }
        else
        {
        business_exist=0;
        }
        data[0]=business_exist;
        data[1]=all_businesses;
        res.send(data);
        });

        1. See you can do that easily, in for loop call some custom function which have callback and contains members_find function. like this

          Business.find({},function(err,businesses){
          if(businesses)
          {
          business_exist=1;
          for(var m in businesses)
          {
          var businessdetail;
          businessdetail = ({ “id”: businesses[m]._id,name': businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”: businesses[m].total_member});
          all_businesses.push(businessdetail);
          find_members(function(data){
          });
          return; // This is very important else code will go below.
          }
          }
          else
          {
          business_exist=0;
          }
          data[0]=business_exist;
          data[1]=all_businesses;
          res.send(data);
          });
          function find_members(callback) {
          //do whatever you want
          callback(data);
          }
          1. I have used callback like this.
            function find_members(businessid,callback) {
            Member.find({“business_id”:businessid},function(err,members){
            membercount=members.length;
            callback(membercount);
            });
            }

            router.get(‘/’, function(req, res, next) {
            var all_businesses=[];
            var data=[];
            var business_exist=0;
            Business.find({},function(err,businesses){
            if(businesses)
            {
            business_exist=1;
            for(var m in businesses)
            {
            var businessdetail;
            var membercount;
            find_members(businesses[m]._id,function(data){
            membercount=data;
            console.log(membercount);//getting member count perfectly.
            });
            console.log(membercount);//getting undefined.
            businessdetail = ({ “id”: businesses[m]._id,’name’: businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”: businesses[m].total_member});
            all_businesses.push(businessdetail);
            }
            }
            else
            {
            business_exist=0;
            }
            data[0]=business_exist;
            data[1]=all_businesses;
            res.send(data);
            });
            });

            The same problem is occurring as previous. If using return then giving socket hang up error.

          2. Try out this please :

            function find_members(businessid,callback) {
            Member.find({“business_id”:businessid},function(err,members){
            membercount=members.length;
            callback(membercount);
            });
            }

            router.get(/, function(req, res, next) {
            var self = this;
            var all_businesses=[];
            var data=[];
            var business_exist=0;
            var membercount;
            var businesses_length;
            Business.find({},function(err,businesses){
            if(businesses)
            {
            business_exist=1;
            businesses_length = businesses.length;
            for(var m in businesses)
            {
            var businessdetail;
            find_members(businesses[m]._id,function(data){
            membercount=data;
            console.log(membercount);//getting member count perfectly.
            });
            if(businesses_length === 0) {
                console.log(membercount);//getting undefined.
            }
            businessdetail = ({ “id”: businesses[m]._id,name': businesses[m].name,”username”: businesses[m].username,”is_active”: businesses[m].is_active,”registration_date”: businesses[m].registration_date,”total_member”: businesses[m].total_member});
            all_businesses.push(businessdetail);
            businesses_length --;

            }
            }
            else
            {
            business_exist=0;
            }
            data[0]=business_exist;
            data[1]=all_businesses;
            res.send(data);
            });
            });
  10. Hello Shahid,

    This was a beautiful, well written article. Just what I was looking for.But I want to receive a mail response from other. How does it work?

    Thanks,

    1. For that you need SMTP box in your system. You might have noticed we are using Google SMTP to send emails so if any one replies it will come to Google one only. I am working on post where we can build our own custom IMAP server along with Node.js. I will update you on same, please subscriber to get email notification. Thanks 🙂

  11. [email protected]:~/Mail$ node server.js

    /home/chandra/Mail/server.js:14
    app.get(‘/’,function(req,res){
    ^^^
    SyntaxError: Unexpected identifier
    at Module._compile (module.js:439:25)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3
    [email protected]:~/Mail$ node -v
    v0.10.25
    [email protected]:~/Mail$ node server.js
    Express Started on Port 3000
    [email protected]:~/Mail$ node server.js
    Express Started on Port 3000
    [email protected]:~/Mail$ node server.js
    Express Started on Port 3000
    { to: undefined, subject: undefined, text: undefined }
    { [RecipientError: Can’t send mail – no recipients defined]
    name: ‘RecipientError’,
    data: ‘250 2.1.0 OK w1sm4352253pdp.25 – gsmtp’,
    stage: ‘mail’ }

  12. Hello Shahid, great article, pretty straightforward, however I have a question.
    What do you need to put in this line

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

    in order to make it work on a production site. I’ve tried putting the domain name of the site as someone in the comments said, but it did not work.
    Thanks

  13. Hi Shahid Shaikh,
    I need an example for sending a mail of particular list item details for given mail id using angularjs can u send me it for me.

  14. Hi,
    I’m getting this error: Failed to load resource: net::ERR_CONNECTION_REFUSED
    What am I doing wrong?

    In my project im using C# as back-end and AngularJS as front-end, do you think it’s a good idea to include this tutorial for sending e-mail or should i look at a solution with C#?

    Thanks! 🙂

  15. Hi, I followed your complete tutorial, but my webpage is not sending email. It is just stuck saying “Sending email. Please wait”. I tried putting some console messages but my entrees are not going to the route.

  16. Hi Sahib,

    Just want to thank you.

    I am not the best programmer (more a hackety-hacker) but currently working on a Ghost Blog theme with a contact form which uses node-mailer.

    Someone provided some basic code which worked fine, but this wasn’t very entertaining, because it used static pages.

    With your code I was able to rewrite it with ajax, and this provides a better base for animations and a much nicer user experience.

    So thank you a lot!

  17. Hi, I used you script, however I downloaded the latest version of nodeMailer and the console shows me that your script is not compatible with the latest version, can you help?

    Thanks!

  18. Hi there,

    First off, this is an awesome tutorial. I’m trying to implement a contact form similar to this on my porfolio page, but when I press send, on the console I get

    “Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://muhsinking.com:3000/send?to=muhsinking%40gmail.com&subject=example+name&text=example+message. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).”

    Do you know what this is about?

    1. Yes try allowing cross origin request in node server. Here is code.

      app.use('*', function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Headers", "X-Requested-With");
        next();
       });

      Paste it on start of router.

  19. I’ve written a little code with node.js and docker (and kue and redis for queueing), which can be used to send out a lots of email; https://github.com/gyulaweber/node_mailsender
    I think it would be cool to have a web frontend, like in this example, but I don’t have enough time to do it’ so feel free to use / fork / … 😉

    Have fun, and thank’s for this great article!

  20. Hi Shahid,

    I tried to write the GET part in pure JavaScript. In server.js, my code is identical to this tutorial’s, and Nodemailer is working properly.

    Here is part of my JS in index.html:

    var data = {to: to, subject: subject, text: text};
    console.log(data); // this logs correct values at this point
    var request = new XMLHttpRequest();
    request.open(‘GET’, ‘http://localhost:3000/send’, true);
    request.send(data);

    In “/send” route, I used
    console.log(“req.query is: ” + req.query);
    to see if the data was successfully sent to here, but it returns an empty object like so {} in the console.

    Nodemailer is working fine, but because to’s value is undefined, it cannot send an email.

    I am wondering if you see any obvious issue here. Thank you for this wonderful tutorial!

  21. I copied the complete code..but when i m clicking on sent mail …its not responding….plz help me out…i m very new to node js….

  22. Hello, thank you for this. Though, I get an error on my server console(expressjs) saying that i must log-in from my browser and that Gmail didnt allow me to send the mail. Im using a regular Gmail account, is there a way to pull through this? Thank you. =)

    ‘I am working on post where we can build our own custom IMAP server along with Node.js.’ I am eagerly waiting for this.

  23. Hi Shahid,

    Just a work of appreciation, everything has been explained so beautifully ! Thanks for posting this ! 🙂

    Regards,
    Shruti

      1. Another Option is not available???
        If available then Plz help….
        This all work good only this problem occur.

  24. Hi Shahid,

    If I want to use my own SMTP service from the server I installed Node.js on, would it be possible instead of using GMail as per section below?

    var smtpTransport = nodemailer.createTransport(“SMTP”,{
    service: “Gmail”,
    auth: {
    user: “[email protected]”,
    pass: “Your Gmail Password”
    }
    });

  25. Hi Shahid,

    I am using this this is working good for my only Gmail account ([email protected]). But now i want to use my business email ([email protected])

  26. Hi Shahid,
    I am trying this emailing messaging but I am getting error on click send_email button.
    { [Error: connect ECONNREFUSED]
    code: ‘ECONNREFUSED’,
    errno: ‘ECONNREFUSED’,
    syscall: ‘connect’,
    stage: ‘init’ }

  27. Hello Shahid,
    I am trying for emailing but I am getting error on clicking send email button.
    { [Error: connect ECONNREFUSED]
    code: ‘ECONNREFUSED’,
    errno: ‘ECONNREFUSED’,
    syscall: ‘connect’,
    stage: ‘init’ }

  28. Hello Shahid,
    Your Tutorial helped me alot,But at the end,i am facing below error.where i was fully confused
    plz help me to fix it.
    { [Error: connect ECONNREFUSED]
    code: ‘ECONNREFUSED’,
    errno: ‘ECONNREFUSED’,
    syscall: ‘connect’,
    stage: ‘init’ }

  29. I am getting the following error on executing Server.js-
    events.js:72
    throw er; // Unhandled ‘error’ event
    ^
    Error: listen EADDRINUSE
    at errnoException (net.js:901:11)
    at Server._listen2 (net.js:1039:14)
    at listen (net.js:1061:10)
    at Server.listen (net.js:1135:5)
    at Function.app.listen (/home/anubha/euprime/email/node_modules/express/lib/application.js:525:24)
    at Object. (/home/anubha/euprime/email/Server.js:32:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

  30. Hello Shahid,
    i used exactly the same code.but when i open localhost:3000 and click on send email
    nothing is happening…
    please reply
    its urgent

        1. Hey Neha,

          Free google account updated their security restricted and do not allow other third party code to send email. Time when i wrote this tutorial they used to but not now, you need to have google apps email account which is premium one to send and receive emails else i think there is some tweak in gmail by which we can send. Will update it here if found any.

          1. Oh ok..Ya thought that would be the problem
            Ty so much
            Do update this if u find an alternate way to do this

  31. RecipientError: Can’t send mail – no recipients defined]
    name: ‘RecipientError’,
    data: ‘250 2.1.0 OK n27sm1161968pfb.53 – gsmtp’,
    stage: ‘mail’

    I am getting this error for the first time I run it
    when i re run it ,the email is being sent.
    how can i resolve the error im facing for the first time

  32. Hello, do u have any idea how to post the form using method=”post” and send email while clicking button..i am getting an error cannot post form..

    Here is my server.js code

    app.post('/contact', function (req, res) {
      var mailOpts, smtpTrans;
      //Setup Nodemailer transport, I chose gmail. Create an application-specific password to avoid problems.
      smtpTrans = nodemailer.createTransport('SMTP', {
          service: 'Gmail',
          auth: {
              user: "[email protected]",
              pass: "gmailpwd"
          }
      });
      //Mail options
      mailOpts = {
          from: req.body.name + ' &lt;' + req.body.email + '&gt;', //grab form data from the request body object
          to: [email protected]',
          subject: 'Website contact form',
          text: req.body.msg
      };
    smtpTrans.sendMail(mailOpts, function (error, response) {
          //Email not sent
          if (error) {
              res.render('contact', { title: 'Raging Flame Laboratory - Contact', msg: 'Error occured, message not sent.', err: true, page: 'contact' })
          }
          //Yay!! Email sent
          else {
              res.render('contact', { title: 'Raging Flame Laboratory - Contact', msg: 'Message sent! Thank you.', err: false, page: 'contact' })
          }
      });
  33. [Error: socket hang up] code: ‘ECONNRESET’

    what is the mean of this error .. can you tell me please….

  34. hi Shahid Shaikh,
    i downloaded your file then i installed npm express and npm node mailer , and also i added my user name and password also , but i got this is error in server command……
    please help me shahid , i am just beginner for node js …..

    C:\Users\Suresh\Downloads\attachments\Node-Mailer-master>node server
    Express Started on Port 3000
    express deprecated res.sendfile: Use res.sendFile instead server.js:27:6
    { to: ‘[email protected]’,
    subject: ‘i am suresh’,
    text: ‘sdsad’ }
    [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 to use it]
    { to: ‘[email protected]’, subject: ‘test’, text: ‘test’ }
    [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 to use it]

      1. hi
        i am getting this error how solve this one??

        > [email protected] start C:\Users\subhash\Desktop\Node-Mailer-master
        > node server.js

        Express Started on Port 3000
        { to: ‘[email protected]’,
        subject: ‘i am gud’,
        text: ‘hi hello how are u?’ }
        [Error: Unsupported configuration, downgrade Nodemailer to v0.7.1 to use it]

  35. Hi Shahid,
    I am getting errout error while sening an email.is that because of the proxy settings.coz i am using proxy which doesn’t allow me to access gmail.

  36. Hi Shahid,
    { [Error: connect ETIMEDOUT 74.125.200.108:465]
    code: ‘ETIMEDOUT’,
    errno: ‘ETIMEDOUT’,
    syscall: ‘connect’,
    address: ‘74.125.200.108’,
    port: 465,
    stage: ‘init’ }
    i am getting this error,is this because of the proxy settings? because i am using a proxy which doesn’t let to use gmail

  37. Hi Shahid,
    Article is very good and something for which I was looking for, before starting my project i would like to confirm that I will be able to covert this app to IOS hybrid app through phonegap.Thanks
    Regards

  38. hi Shahid sir
    am using this code
    package com.mycompany.design;

    import java.awt.Color;

    import java.util.logging.Level;
    import java.util.logging.Logger;

    import javax.mail.MessagingException;
    import javax.swing.JOptionPane;

    /**
    *
    * @author IBN
    */
    public class Mailsend extends javax.swing.JFrame {

    /**
    * Creates new form Mailsend
    */
    public Mailsend() {
    initComponents();

    getContentPane().setBackground(new Color(130, 123, 96));
    setTitle(“Send puzzle expression to sever”);

    }

    /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
    @SuppressWarnings(“unchecked”)
    //
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    to = new javax.swing.JTextField();
    to.setBackground(new Color( 255, 235, 205));
    jLabel3 = new javax.swing.JLabel();
    sub = new javax.swing.JTextField();
    sub.setBackground(new Color( 255, 235, 205));
    jLabel4 = new javax.swing.JLabel();
    msg = new javax.swing.JTextField();
    msg.setBackground(new Color( 255, 235, 205));
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setMinimumSize(new java.awt.Dimension(700, 700));
    getContentPane().setLayout(null);

    jLabel1.setFont(new java.awt.Font(“algeria”, 1, 20)); // NOI18N
    jLabel1.setText(“Sending Mail”);
    jLabel1.setForeground(new Color(247, 13, 26));
    getContentPane().add(jLabel1);
    jLabel1.setBounds(176, 40, 201, 24);

    jLabel2.setFont(new java.awt.Font(“algeria”, 1, 20)); // NOI18N
    jLabel2.setText(“Sever mail id”);
    // jLabel2.append(“[email protected]”);
    jLabel2.setForeground(new Color(247, 13, 26));
    getContentPane().add(jLabel2);
    jLabel2.setBounds(49, 114, 200, 30);

    to.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    toActionPerformed(evt);
    }
    });
    getContentPane().add(to);
    to.setBounds(200, 114, 190, 30);

    jLabel3.setFont(new java.awt.Font(“algeria”, 1, 20)); // NOI18N
    jLabel3.setText(“Subject”);
    jLabel3.setForeground(new Color(247, 13, 26));
    getContentPane().add(jLabel3);
    jLabel3.setBounds(49, 198, 200, 30);
    jLabel4.setFont(new java.awt.Font(“algeria”, 1, 20)); // NOI18N
    jLabel4.setText(“puzzle expression”);
    jLabel4.setForeground(new Color(247, 13, 26));
    getContentPane().add(jLabel4);
    jLabel4.setBounds(20, 300, 200, 30);

    sub.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    subActionPerformed(evt);
    }
    });
    getContentPane().add(sub);
    sub.setBounds(200, 200, 190, 30);

    msg.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    msgActionPerformed(evt);
    }
    });
    getContentPane().add(msg);
    msg.setBounds(200, 270, 190, 100);

    jButton1.setFont(new java.awt.Font(“algeria”, 1, 18)); // NOI18N
    jButton1.setText(“Send”);
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    try {
    jButton1ActionPerformed(evt);
    } catch (MessagingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    });
    getContentPane().add(jButton1);
    jButton1.setBounds(277, 400, 90, 31);
    jButton1.setBackground(new Color(227, 138, 174));

    pack();
    }//

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) throws javax.mail.MessagingException {
    String t = to.getText();
    String s = sub.getText();
    String c = msg.getText();

    mail m = new mail();
    m.mailsend(t,s,c);

    JOptionPane.showMessageDialog(null, “Sent sucessfully”,””,1);
    // TODO add your handling code here:
    }

    private void toActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }

    private void subActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }

    private void msgActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
    */
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if (“Nimbus”.equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClassName());
    break;
    }
    }
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(Mailsend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(Mailsend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(Mailsend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(Mailsend.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Mailsend().setVisible(true);
    }
    });
    }
    // Variables declaration – do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField msg;
    private javax.swing.JTextField sub;
    private javax.swing.JTextField to;
    // End of variables declaration
    }
    it was working fine for my project suddenly i am facing authentication error kindly help me

  39. Hi Shahid,
    I’m trying do the same thing as you have done.
    But when I click on send-Email button.
    It says Sending Email… But nothing happens

    Can you please help me with this?

      1. Its not showing any Error even in console. Its just saying Sending Email and nothing is happening.
        Or can you give angularJS code for the same instead of jQuery

      2. Hey Shahid it worked now after trying out few options.
        But I want to do the same in angular not in jQuery
        So can you help me by providing the angular code for the same instead of jquery?

        Thank you

  40. Hi, thanks for this tutorial, i used our mail host instead of gmail and it worked.
    Now i’m trying to customize it with angular 2 instead of jQuery

  41. Hi Shahid,

    I’m getting TypeError: Can’t create property ‘mailer’ on string ‘SMTP’ in node

    Can U Help Me Plz…????

      1. Hi I get this error as well, and I installed the dependencies, including express and nodemailer, by using npm install,
        the complete error message is this:
        C:\wamp\www\mean-projects\nodemail\node_modules\nodemailer\lib\mailer\index.js:4
        5
        this.transporter.mailer = this;
        ^

        TypeError: Cannot create property ‘mailer’ on string ‘SMTP’
        at Mail (C:\wamp\www\mean-projects\nodemail\node_modules\nodemailer\lib\mail
        er\index.js:45:33)
        at Object.module.exports.createTransport (C:\wamp\www\mean-projects\nodemail
        \node_modules\nodemailer\lib\nodemailer.js:40:14)
        at Object. (C:\wamp\www\mean-projects\nodemail\server.js:8:32)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
        at Function.Module._load (module.js:438:3)
        at Module.runMain (module.js:604:10)
        at run (bootstrap_node.js:394:7)

        Could you help us please?

          1. same error what he is facing….

            d:\JOSHUA\mail\node_modules\nodemailer\lib\mailer\index.js:45
            this.transporter.mailer = this;
            ^

            TypeError: Cannot create property ‘mailer’ on string ‘SMTP’
            at Mail (d:\JOSHUA\mail\node_modules\nodemailer\lib\mailer\index.js:45:33)
            at Object.module.exports.createTransport (d:\JOSHUA\mail\node_modules\nodemailer\lib\nodemailer.js:46:14)
            at Object. (d:\JOSHUA\mail\server.js:8:32)
            at Module._compile (module.js:571:32)
            at Object.Module._extensions..js (module.js:580:10)
            at Module.load (module.js:488:32)
            at tryModuleLoad (module.js:447:12)
            at Function.Module._load (module.js:439:3)
            at Module.runMain (module.js:605:10)
            at run (bootstrap_node.js:420:7)

  42. In my case problem was in following code:
    var smtpTransport = nodemailer.createTransport(‘SMTP’,{
    service: “Gmail”,
    auth: {
    user: “[email protected]”,
    pass: “********”
    }
    });

    I removed ‘SMTP’ and now, it is working fine.

  43. Pls mine doesn’t even do anything. It simply shows
    Sending E-mail…Please wait.
    Need your help. Thanks a million

Leave a Reply

Your email address will not be published. Required fields are marked *