How to send mail using nodemailer in node js?

Folder Structure:

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

email config.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="https://dev.to/" 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

Thanks.
You can follow us on:
youtube
instagram

Leave a Comment