Sending mails from node js

Sending mails from node js web application

today we will be learning about how to Sending mails from node js. To make a simple website at first we need to initialize a simple express app we require express, path, body-parser, nodemailer.

First we need to make install all of these modules with.

 npm install express body-parser nodemailer
 ejs
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

we initialize express with var app = express();

than we initialize body parser to send json response and urlencoded to false.

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

than we make our root route in the application with app.get() and we pass a function to it of

app.get('/', function(req,res){
    console.log('hello world');
    res.send('hello world');
});

request and response to send data to use at last we start a webserver on port 3000

app.listen(3000);

console.log('server is running on port 3000');

Final Code

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

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

app.get('/', function(req,res){
    console.log('hello world');
    res.send('hello world');
});

app.listen(3000);

console.log('server is running on port 3000');

2. Adding View engine to node

We need a view engine to server html and other files in a node express application. So in order to do that we will use jade as our view engine. Initialize it This is just for ease but later we will switch to ejs.

We use these two lines to initialize the view engine which we will use to server html and other files to our web app.

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

after that we will render the html file like example below.

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

Now we need to create a directory named views in our folder because as we mentioned app.set('views', path.join(__dirname, 'views')); views as a parameter to this path to server our views or jade files and we create a index.jade file in it and write h3 hello world for h3

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

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

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

app.listen(3000);

console.log('server is running on port 3000');

3. Making a contact get and post route

to make and server the /contact route we can just make one like we did earlier

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

Now that we have a route to /contact we can make a page contact i switched to EJS for view engine because it is easier to read and understand. we go to our views folder and make a contact.ejs file here we write the code of our form which we will use to send a mail to us when ever someone submits the form

<%- include('partials/header.ejs') %>.
<body>

<main role="main" class="container">

    <body class="bg-light">
        <div class="container">
      <div class="py-5 text-center">
        <form method="POST" action="/contact/send">
            <div class="form-row">
              <div class="form-group col-md-6">
                <label for="name">Name</label>
                <input type="text" class="form-control" name='name' id="name" placeholder="Name">
              </div>
              <div class="form-group col-md-6">
                <label for="mail">Email</label>
                <input type="email" class="form-control" name='email' id="mail" placeholder="Email">
              </div>
            </div>
            <div class="form-row">
              <div class="form-group col-md-12">
                <label for="msg">Message</label>
                <textarea class="form-control" name='message' id="msg"> </textarea>
              </div>
            </div>
     
            <button type="submit" class="btn btn-primary">Sign in</button>
          </form>
      </div>
    
      <div class="row">
        <div class="col-md-4 order-md-2 mb-4">
           
        </div>
    </div>
</main>
<%- include('partials/footer.ejs') %>.

The code above includes these two partials which are just bootstrap head and footer tags

Header

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v4.1.1">
    <title>Album example · Bootstrap</title>

    <link rel="canonical" href="<https://getbootstrap.com/docs/4.5/examples/album/>">

    <!-- Bootstrap core CSS -->
<link href="/css/bootstrap.css" rel="stylesheet" >

    <!-- Favicons -->
<link rel="apple-touch-icon" href="/docs/4.5/assets/img/favicons/apple-touch-icon.png" sizes="180x180">
<link rel="icon" href="/docs/4.5/assets/img/favicons/favicon-32x32.png" sizes="32x32" type="image/png">
<link rel="icon" href="/docs/4.5/assets/img/favicons/favicon-16x16.png" sizes="16x16" type="image/png">
<link rel="manifest" href="/docs/4.5/assets/img/favicons/manifest.json">
<link rel="mask-icon" href="/docs/4.5/assets/img/favicons/safari-pinned-tab.svg" color="#563d7c">
<link rel="icon" href="/docs/4.5/assets/img/favicons/favicon.ico">
<meta name="msapplication-config" content="/docs/4.5/assets/img/favicons/browserconfig.xml">
<meta name="theme-color" content="#563d7c">

    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }
    </style>
    <!-- Custom styles for this template -->
    <link href="album.css" rel="stylesheet">
  </head>
  <body>
    <header>
  <div class="collapse bg-dark" id="navbarHeader">
    <div class="container">
      <div class="row">
        <div class="col-sm-8 col-md-7 py-4">
          <h4 class="text-white">About</h4>
          <p class="text-muted">Add some information about the album below, the author, or any other background context. Make it a few sentences long so folks can pick up some informative tidbits. Then, link them off to some social networking sites or contact information.</p>
        </div>
        <div class="col-sm-4 offset-md-1 py-4">
          <h4 class="text-white">Contact</h4>
          <ul class="list-unstyled">
            <li><a href="#" class="text-white">Follow on Twitter</a></li>
            <li><a href="#" class="text-white">Like on Facebook</a></li>
            <li><a href="#" class="text-white">Email me</a></li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</header>

<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarsExampleDefault" aria-controls="navbarsExampleDefault" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarsExampleDefault">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/about">About</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="/contact">contact</a>
      </li>
      
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="text" placeholder="Search" aria-label="Search">
      <button class="btn btn-secondary my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>

Footer

<footer class="text-muted">
    <div class="container">
      <p class="float-right">
        <a href="#">Back to top</a>
      </p>
      <p>Webapp is © Nemocorp!</p>
    </div>
  </footer>
  <script src="<https://code.jquery.com/jquery-3.5.1.slim.min.js>"></script>
        <script>window.jQuery || document.write('<script src="/docs/4.5/assets/js/vendor/jquery.slim.min.js"><\\/script>')</script><script src="/docs/4.5/dist/js/bootstrap.bundle.min.js" ></script></body>
  </html>

after copying this code in contact.ejs our page will look something like this

4. Handling the form and Sending mail through nodemailer

we first make our form and on the backend, we take that post request and use nodemailer’s transporter function to make it send mails


// it wont work if you dont use allow less secure apps <https://myaccount.google.com/lesssecureapps>
app.post('/contact/send', function(req,res){
    var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {user: '[email protected]',pass: 'password'}
    });

    var mailOptions = { 
        from: 'Sheeraz ali <[email protected]>',
        to: '[email protected]',
        subject: 'websiite submision',
        text: 'You have submisson with soo and so things in it Name: ' + req.body.name + 'Email ' + req.body.email + 'Message ' + req.body.message,
        email: '<p>you have mail from so and so </p>'
    }

    transporter.sendMail(mailOptions,function(error,info){
        if(error){
            console.log(error)
            res.redirect('/');
        }else{
            console.log('Message Sent' + info.response);
        }
    })
});

Final Code

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var nodemailer = require('nodemailer');

var app = express();

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));

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

app.get('/about', function(req,res){
    res.render('about')
});

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

// it wont work if you dont use allow less secure apps <https://myaccount.google.com/lesssecureapps>
app.post('/contact/send', function(req,res){
    var transporter = nodemailer.createTransport({
    service: 'Gmail',
    auth: {user: '[email protected]',pass: 'password'}
    });

    var mailOptions = { 
        from: 'Sheeraz ali <[email protected]>',
        to: '[email protected]',
        subject: 'websiite submision',
        text: 'You have submisson with soo and so things in it Name: ' + req.body.name + 'Email ' + req.body.email + 'Message ' + req.body.message,
        email: '<p>you have mail from so and so </p>'
    }

    transporter.sendMail(mailOptions,function(error,info){
        if(error){
            console.log(error)
            res.redirect('/');
        }else{
            console.log('Message Sent' + info.response);
        }
    })
});

app.listen(3000);

console.log('server is running on port 3000');

In order for this to work you need to turn less secure apps on for the sending account

So that was a way for sending mails from node js you can read other things on my blog related to web development here

Posts created 10

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top