How to Send Mail using nodemailer in node js ?

akshdesai1

AKSH DESAI

Posted on November 12, 2022

How to Send Mail using nodemailer in node js ?

Folder Structure :

Folder Structure of Output

App.js Code:

const express = require('express');
const ejs = require('ejs');
const transporter = require("./config/emailConfig.js");

const app = express();
const PORT = 8000;

// Set Template Engine 
app.set('view engine', 'ejs')
app.use(express.urlencoded({extended: false}))

app.get("/", (req, res) => {
    return res.render("index");
});

app.post("/", async (req, res) => {
    const { email } = req.body;

    try {
        let info = await transporter.sendMail({
            from: "laughtercomedy708@gmail.com", // sender address
            to: email, // list of receivers
            subject: "Express - Nodemailer", // Subject line
            text: " Email Send Successfuly.", // plain text body
        })
        return res.json({ "status": "success", "message": "Password Reset Email Sent... Please Check your Email."})
    } catch (error) {
        return res.json({ "status1": "failed", "message": error.message })
    }
})

app.listen(PORT, () => {
    console.log(`Server is Listening at ${PORT} Port.`);
})
Enter fullscreen mode Exit fullscreen mode

package.json code:

{
  "name": "q.11",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "dev": "nodemon app"
  },
  "keywords": [],
  "author": "aksh desai",
  "license": "ISC",
  "dependencies": {
    "ejs": "^3.1.8",
    "express": "^4.18.2",
    "nodemailer": "^6.8.0"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

Enter fullscreen mode Exit fullscreen mode

emailConfig.js code:-

const nodemailer = require("nodemailer");

let transporter = nodemailer.createTransport({
    host: "smtp.gmail.com",
    port: 587,
    // secure: false, // true for 465, false for other ports
    auth: {
        user: "laughtercomedy708@gmail.com", // generated ethereal user
        pass: "your app password", // generated ethereal password
    }
})

module.exports = transporter;
Enter fullscreen mode Exit fullscreen mode

index.ejs code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1> Hello World </h1>

    <form action="/" method="post"> 
        <input type="email" name="email" required> <br>
        <input type="submit" value="submit">
    </form>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Output Image:-

Output Image

Thank You.
You can follow us on:
Youtube
Instagram

💖 💪 🙅 🚩
akshdesai1
AKSH DESAI

Posted on November 12, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related