Breaking

How To Send Email with NodeJS and Nodemailer using Gmail | NodeJS Tutorial for Beginner

 


To run this project you need to do some setup

  1. Install nodejs and postman on you computer
  2. create a folder and open Terminal / Command  Prompt/ Power Shell whiten this folder 
  3. Make sure you don't have 2 step verification of your gmail 
  4. Turn on less secure app access from https://myaccount.google.com/lesssecureapps
  5. Copy everything from index.js (Below) and make a file with same name and paste it
  6. Replace gmail address and password from index.js
  7. And use following commands

npm install nodemon express nodemailer body-parser

Initilize your nodejs project (Make sure your project folder name has no space and no uppercase)

npm init -y

Install essential packages using npm

npm install nodemon express nodemailer body-parser

Install essential packages using npm

node index.js



index.js


// Fast, unopinionated, minimalist web framework for node.
const express = require('express');
// Parse incoming request bodies in a middleware before your handlers, available under the
const bodyParser = require('body-parser');
// Send e-mails from Node.js – easy as cake! 🍰✉️
const nodemailer = require('nodemailer');
// CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
const cors = require('cors');





const app = express();



require('dotenv').config();


// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());
app.use(cors());





// POST ROUTE FOR POST DATA TO SERVER
app.post('/mail', async (req, res, next) => {
    // DESTRUCTURING VARIABLE AND SETTING IT WITH DIFFERENT NAME
    let { email, subject, text } = req.body;
    // console.log(mailContent);



     // create reusable transporter object using the default transport
    let transporter = nodemailer.createTransport({
        // host: "localhost",
        service: "gmail",
        port: 465, 
        secure: false, // true for 465, false for other ports
        auth: {
            // SENDER EMAIL AND PASSWORD
            user: sendergmailaddress@gmail.com,   // generated ethereal user
            pass: recivergmailpassword   // generated ethereal password
        }
    });



    const message = {
        // SENDER MAIL
        from: process.env.EMAIL,
        //  REVICER MAIL
        // to: "recivergmailaddress@gmail.com",
        to: email,
        subject: subject,
        text: text,
        html: "<p>HTML version of the message</p>"
    };



    try {
        // send mail with defined transport object
        let info = await transporter.sendMail(message);
        res.status(200).json({
            "Message": message
        });
        console.log(info);
    } catch (error){
        res.send(error);
        console.log("error: ", error);
    }
    transporter.close();

});


const PORT = process.env.PORT || 4000;
app.listen(PORT, () => console.log("server is running on " + PORT));

Now open postman


Create a new request and do same as mine change gmail address and send it 

Now check inbox of reciver.

Check out video tutorial



Thank you!

No comments:

Powered by Blogger.