Sending Emails Using Nodemailer And Gmail

The easiest way to send an email via your Nodejs application is nodemailer. There are only 3 simple steps. From here onwards this article will explain how you can send an email via an express.js server.

First, you need to create an npm project to initialize it to install express.js. For that create a folder in a preferred location(folder name will be the project name) and open the terminal and move to that folder location using cd command.

Then in there terminal run the following command.

npm init -y

Then you can install express to this project. With Express you need another 2 libraries to work with express. They are body-parser and cores. Run the following command to install them.

npm install express body-parser cors

Next, install nodemon to keep running the server and to identify the changes that you do to the code and restart the server with the changes.

npm install -g nodemon 

Next, open the project in vs code using the code

code .

Now we can start coding the server. So create a server.js file inside the project. Then import all the libraries required and create an instance from them.Also, define a port to run the server.


//importing express
const express = require('express');
//create new express instance
const app = express();
//importing bodyParser and cors
const bodyParser = require('body-parser');
const cors = require('cors');
//import nodemailer email service
const nodemailer = require('nodemailer');
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
//making router instance
const appRoutes = express.Router();
//port to run the server
const PORT = process.env.PORT || 4001;
//add middleware cors and bodyParser to express
app.use(cors());
app.use(bodyParser.json());

Here when defining the port; process.env.PORT || 4001 means if the environment variables set the server is run on that server or else the server is run on port 4001.

Next, create a URL for the server and start up the server.


app.use('/api/gov',appRoutes);

app.listen(PORT,function(){
    console.log("Server is running on PORT: "+PORT);
});

Next, open the terminal in vs code and run the following command to start up the server.

nodemone server 

New You will see a message “Server is running on PORT: ” on the terminal

If the server is running properly you can create an HTTP endpoint to access the server. Inside the endpoint, you can use nodemailer and send the email.

appRoutes.route('/send').post(function(req,res){
 var output=`This is a sample email sent from nodemailer`;

 let transporter = nodemailer.createTransport({  
                         host: 'smtp.gmail.com',
                         port: 465,
                         secure: true, 
                         auth: { 
                              user: '', pass: ''
                            } 
                  });  

 let mailOptions = { 
          from: '', to:req.body.email,
          subject: 'Email Subject 1',
          html: output 
         };

 transporter.sendMail(mailOptions,(error, info) => { \
         if (error) {
              return console.log(error);
              res.status(400).json({message:"email sent fail"}); 
   } 
     res.status(200).json({message:"email sent"});
     console.log('Message %s sent: %s', info.messageId, info.response); 
   });
});

Finally, you need to allow less secure apps in google account. If not Google will not allow the system to use the account. You can do it by going to this link.

Leave a comment

Start a Blog at WordPress.com.

Up ↑

Design a site like this with WordPress.com
Get started