Send Email From NODE JS using Nodemailer and Using Gmail App Password feature (Disabled Less Secure App Access)


    INTRODUCTION

    To ship an e-mail in Node.Js, use the nodemailer module. The nodemailer is a module that offers you the capability to send emails without hassle easily. It makes use of a easy Mail transfer Protocol (SMTP), a protocol for sending e-mail messages among servers. Maximum e mail systems that send mail over the net supports SMTP-primarily based sending.

    Nodemailer is a module for Node.Js applications to allow easy as cake electronic mail sending. The undertaking got started out back in 2010 whilst there has been no sane choice to ship e-mail messages, nowadays it's miles the answer most Node.Js customers turn to by way of default.

    PREREQUISITE

    - NODE JS and NPM should have already installed in your computer.
    - Basic knowledge of 
    • NODE, EXPRESS
    • nodemailer
    • nodemon 
    and after creating project install express, nodemailer package and more necessary packages
    on your project by following commands:
    npm install express
    npm install nodemailer
    


    CREATING PROJECT

    Create a NOJE.JS project by entering the command "npm init -y" ,  Here -y is optional
    After hitting the command you get package.json and following response in terminal


    CODE EXAMPLES

    • Project Structure

    • Add   "type": "module"  in package.json file  and Add  "start": "nodemon ."  inside 'scripts' components in package.json file .

    • creating server
      
      
    import bodyParser from 'body-parser';
    import express from 'express';
    import sendEmail from './sendEmail.js';
    const app=express()
    
    app.set('view engine','ejs')
    
    app.use(express.json())
    app.use(bodyParser.urlencoded({extended:true}))
    app.use(bodyParser.json())
    
    app.listen(5000,(req,res)=>{
        console.log("Server Started on Port 5000 ");
    })
      
    • creating routes for sending email
      
    app.get('/',(req,res)=>{
        res.render('index')
    })
    
    app.post('/sendEmail',(req,res)=>{
        const {email,subject,message}=req.body
        var sent= sendEmail(email,subject,message);
        if(sent!='0'){
            res.send('Email Sent Successfully');
        }
        else{
            res.send('Something Went Wrong');
        }
    })
      
      
    • creating email sending module or function
      
    import nodemailer from 'nodemailer'
    function sendEmail(email,subject,message){
            var email = email;
            var subject = subject;
            var message=message;
            var mail = nodemailer.createTransport({
              service:'gmail',
              auth: {
                user: "abc@gmail.com", // Your email id
                pass: "pass", // generated password of app password from  gmail
              },
            });
            var mailOptions = {
              from: "abc@gmail.com", //your email
              to: email,
              subject: subject,
              html:message
            };
            mail.sendMail(mailOptions, function (error, info) {
              if (error) {
                console.log(error);
              } else {
                console.log(0);
              }
            });
          }
    export default sendEmail;
      
    • Creating front end in ejs: index.ejs
      
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Send Email</title>
    </head>
    <body>
        <div class="container" style="width: 38rem;">
    
        <form method="post" action="/sendEmail">
            <legend>SEND EMAIL</legend>
    
            <div class="mb-3">
              <label class="form-label">To</label>
              <input type="email" name="email" required class="form-control" placeholder="Email">
            </div>
            <div class="mb-3">
                <label class="form-label">SUBJECT</label>
                <input type="text" name="subject" class="form-control" placeholder="subject">
            </div>
            <div class="mb-3">
                <label class="form-label">BODY OR MESSAGE</label>
                <textarea class="form-control" name="message" required rows="5" placeholder="Message Here..."></textarea>
            </div>
            <button type="submit" class="btn btn-primary">Send</button>
          </form>
        </div>
    
    </body>
    </html>
    
    
    • gcreating App Password for our node app in Gmail
      • Go to Security Tab and Click on App Password:  if App Password option doesn't appear on your screen then you should enable 2-Step Verification

      • Click on Select App and Select 'Other(Custom Name)' option as below
      • Enter Name of Project
      • Now Click on Generate and You will get Password for app


    RUNNING A PROJECT

    Run Your Project by Simply typing "npm start"


    RESULT / OUTPUT




    0 Comments