Processing Contact Form with Node.js

In this article we'll going to create a simple nodejs and express application and we will implement nodeMailer for processing the form, if you don't know what's nodeMailer, it's simply a mailing module for nodejs.

For this article I'll be using gmail as the smtp, you can also use gmail if you want, but you may have some issues with security. Read the Gmail usage guide on the Nodemailer website to have a clear understanding.

For development it's absolutely fine, but you shouldn't use it with a production application, if you've signed up for a hosting account then you should have a smtp server that you can use with you emails.

With that said let's get started with the setup. The only thing you need is node.js installed on your computer.

The setup

The markup (which will be placed in the .handlebars file ) we'll create the file soon

cd into your project folder and run this command

        
          npm init -y
        
      

Installing the dependencies

What we want to do now is install some dependencies for our application, we need express, body-parser, nodemailer and express-handlebars for the view engine.

    
      npm install --save express body-parser express-handlebars nodemailer
    
  

Once there are installed, create the entry file. "index.js" or "app.js" whatever you prefer.

Bringing the dependencies

    
      const express = require('express');
      const nodemailer = require('nodemailer');
      const exBars = require('express-handlebars');
      const bodyParser = require('body-parser');
      const path = require('path');

    
  

Initialize express

    
      const app = express();
    
  

View engine setup

    
      app.engine('handlebars', exBars());
      app.set('view engine', 'handlebars');
    
  

body-parser middleware

    
      app.use(bodyParser.urlencoded({extended: false}));
      app.use(bodyParser.json());
    
  

Creating the stactic folder

Create a folder, name it public. Inside that folder create a css folder because that where you'll be putting your css files.

Now we need to let express know that that's the folder we want to use. So we'll set the path like this.

    
      app.use('/public', express.static(path.join(__dirname, 'public')));
    
  

Creating our view

In your root directory of the your project create a folder, name it views, inside that views folder create a handlebars file, I called mine contact.handlebars This is where you'll put your contact form. as I mentioned in the markup setup

The route

Let's create the route (inside your js file)

    
      app.get('/', (req, res) => {
      res.render('contact')
    });
    
  

Create the server

    
    app.listen(3000, () => {console.log('Server Started');
    
  

Inside the handlebars file where you put your form. The method and action for the form should be like this, also add a variable to inside the form to display success messages when it is sent

Remember it's a handlebars file so when use this {{}} instead, and make sure your button type is set to submit

Creating a post route for the submition

Inside your js file

        
          app.post('/send', (req, res) => {
            //The output string and nodemailer implementation will all be inside here
         }
        
      

Creating the output string

Inside of the post route

implementing Nodemailer

Inside the post route, it won't work if you put it outside of the post route

        
        let transporter = nodemailer.createTransport({
            host: 'smtp.gmail.com',
            port: 587,
            secure: false, // true for 465, false for other ports
            auth: {
                user: 'user@gmail.com', // generated ethereal user
                pass: 'userpassword' // generated ethereal password
            },
            tls:{
                rejectUnauthorized: false
            }
        });

        // setup email data with unicode symbols
        let mailOptions = {
            from: '"Contact form" ', // sender address
            to: 'reciever@gmail.com', // list of receivers
            subject: 'From node app', // Subject line
            text: 'Hello world?', // plain text body
            html: output // html body
        };

        // send mail with defined transport object
        transporter.sendMail(mailOptions, (error, info) => {
            if (error) {
                return console.log(error);
            }
            console.log('Message sent: %s', info.messageId);
            console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));

            res.render('contact', {msg: 'Message sent'});
        });
    })

        
      

Now run it

To run it, cd to the root directory of your project then run this command node followed by the name you called your js file. example assuming I called mine app.js all I have to do is run this command node app