Send An Email In Node.js

Introduction

In this article, we will learn how to send an email in node.js. As you know, sending emails in any application is an important function. First, I will setup node.js application using NPM commands; then I will implement email function. To implement the main function, there are several packages available. We will use "nodemailer" package. We will install this package using the following npm command
 
npm install nodemailer

Background

You should have a basic understanding of the node.js application, JavaScript, and HTML.

Code implementation

Requirement

  • Node.js version should be greater than 6.0
  • Express.js
  • One text editor like Sublime or any other

Create Node.js Application

First, we will create a package.json file which is very important and contains information of all the configuration and packages included in our application. So, let's create package.json file using command "npm init". Open terminal and type command "npm init". It will ask to enter all the details about the configuration.

After entering these details, it will create configuration file automatically in your application folder. The configuration file will contain the information regarding project configuration.

Now, we have to install Express with the latest version. To install the Express.js framework, we will execute the npm command -

npm install express
 
It will install the latest version of Express. Ater Express is installed, we will install "nodemailer" using -

npm install nodemailer 
 
Nodemailer will be used to send the email in node.js. To send the email in node.js, there are many packages available but we will use nodemailer package.

After the installation of all these packages, the package.json file will look like the following.

  1. {  
  2.   "name""send-main-using-nodejs",  
  3.   "version""1.0.0",  
  4.   "description""we will send mail using nodejs with gmail authentication",  
  5.   "main""server.js",  
  6.   "scripts": {  
  7.     "test""echo \"Error: no test specified\" && exit 1"  
  8.   },  
  9.   "author""Jyoti",  
  10.   "license""ISC",  
  11.   "dependencies": {  
  12.     "nodemailer""^4.0.1",  
  13.     "express""^4.8.0"  
  14.   }  
  15. }  

In the above package.json file, we can see the installed packages information like Express having the version 4.8.0 and nodemailer having the version 4.0.1. If you look at the main script in the package.json file, you will notice that command that the start of the application is "main": "server.js". To start the application, you will have to execute the script "node server.js"

Now, we will create a new file named "server.js" in our application and will include all the required files. In the server.js file, we will call the references to Express and nodemailer.

Now, you can see that we have created the smtptransport object from nodemailer. It will authenticate and send the mail. Now, you have to pass the one email id and password of Gmail. It will be used to authenticate and then send the email to the recipients.

Find the below server.js file.

  1. var express    = require('express');  
  2. var nodemailer = require("nodemailer");  
  3. var app        = express();  
  4.   
  5. var smtpTransport = nodemailer.createTransport({  
  6.     service: "gmail",  
  7.     host: "smtp.gmail.com",  
  8.     auth: {  
  9.         user: "gmailemailId",  
  10.         pass: "password"  
  11.     }  
  12. });  
  13.   
  14. app.get('/', function(req, res) {  
  15.     res.sendfile('index.html');  
  16. });  
  17.   
  18. app.get('/sendmail', function(req, res) {  
  19.     var mailOptions = {  
  20.         to:"toemalid",  
  21.         subject:"Email from nodemailer",  
  22.         html:'<div>Name: '+ req.query.name +'</div><div>Email: '+ req.query.email +'</div><div>Mobile: '+ req.query.mobile +'</div><div>Message: '+ req.query.message +'</div>'  
  23.     }  
  24.     smtpTransport.sendMail(mailOptions, function(error, response) {  
  25.      if(error) {  
  26.         res.end("error");  
  27.      } else {  
  28.         res.end("sent");  
  29.      }  
  30.    });  
  31. });  
  32.   
  33. app.listen(3000, function() {  
  34.     console.log("Application started on http://localhost:3000/");  
  35. });  
Now, create the HTML page which contains a contact form.
  1. <html>  
  2. <head>  
  3.   <title>Send Message in Node.js</title>  
  4.   <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  
  5. </head>  
  6. <body>  
  7. <div id="container">  
  8. <h1>Send Main Function In Node.JS</h1>  
  9. <table>  
  10.     <tr>  
  11.         <td>Name: </td>  
  12.         <td><input type="text" name="txtname" id="txtname" placeholder="Enter Name"></td>  
  13.     </tr>  
  14.     <tr>  
  15.         <td>Email: </td>  
  16.         <td><input type="text" name="txtemail" id="txtemail" placeholder="Enter Email"></td>  
  17.     </tr>  
  18.     <tr>  
  19.         <td>Mobile: </td>  
  20.         <td><input type="text" name="txtmobile" id="txtmobile" placeholder="Enter Mobile"></td>  
  21.     </tr>  
  22.     <tr>  
  23.         <td>Message: </td>  
  24.         <td>  
  25.           <textarea id="txtmessage" name="txtmessage" cols="40" rows="5" placeholder="Enter Message"></textarea>  
  26.         </td>  
  27.     </tr>  
  28.     <tr>  
  29.         <td> </td>  
  30.         <td>  
  31.             <button id="btnsendemail">Send</button>  
  32.         </td>  
  33.     </tr>  
  34.     <tr>  
  35.         <td></td>  
  36.         <td>  
  37.             <span id="message"></span>  
  38.         </td>  
  39.     </tr>  
  40. </table>  
  41. </div>  
  42. <script>  
  43. $(document).ready(function(){  
  44.     var name;  
  45.     var email;  
  46.     var mobile;  
  47.     var message;  
  48.     $("#btnsendemail").click(function() {        
  49.         name    = $("#txtname").val();  
  50.         email   = $("#txtemail").val();  
  51.         mobile  = $("#txtmobile").val();  
  52.         message = $("#txtmessage").val();  
  53.         $("#message").text("Sending Email please wait ...");  
  54.         $.get("/sendmail",  
  55.             {  
  56.                 name: name,  
  57.                 email: email,  
  58.                 mobile: mobile,  
  59.                 message: message  
  60.             },  
  61.         function(data) {  
  62.         if(data == "sent") {  
  63.             $("#message").html("Email has been send successfully.");  
  64.         }  
  65.       });  
  66.     });  
  67. });  
  68. </script>  
  69. </body>  
To run this project, enter "node server.js" in terminal.

Then, type "localhost:3000" in any browser followed by an Enter.

The page will open; fill in the form and click the button to send mail. Don't forget to enter the GMail address and password for authentication.

Up Next
    Ebook Download
    View all
    Learn
    View all