Sending OTP to Gmail Using Nodemailer - A Practical Guide -🙏 Namaste Node Js

0
Sending OTP to Gmail Using Nodemailer - A Practical Guide
Nodemailer Tutorial Poster

What is Nodemailer?

Nodemailer is a module for Node.js applications that allows you to send emails easily. It supports multiple email services, including Gmail, Outlook, and more, using their SMTP (Simple Mail Transfer Protocol) servers.

Why Use Nodemailer?

Nodemailer is an excellent choice for sending emails in web applications. It's particularly useful for sending OTPs for password resets, email confirmations, and other transactional emails. It supports secure email sending via OAuth2 and other authentication methods.

Step-by-Step Nodemailer Setup

  1. First, install Nodemailer using npm: npm install nodemailer
  2. Create an input form to accept the user's email address.
  3. Validate if the email exists in the database before proceeding.
  4. Set up an EJS template for the 'Forget Password' page.
  5. Use a POST request to send OTP to the user via Nodemailer.

Sending OTP to Gmail Using Nodemailer

We will use Nodemailer to send an OTP (One-Time Password) to the user's Gmail. First, we need to create a function in the controller to handle the email sending process. Below is an example of how to send the OTP using Nodemailer:


const nodeMailer = require('nodemailer');
require('dotenv').config();

const sendEmail = async (options) => {
    const transporter = nodeMailer.createTransport({
       host: "smtp.zoho.com",
       port: 465,
       auth: {
           user: process.env.EMAIL,
           pass: process.env.PASSWORD
       }
    });

    const mailOptions = {
        from: 'Your Name ',
        to: options.email,
        subject: options.subject,
        text: "Your OTP is " + options.otp
    };

    await transporter.sendMail(mailOptions);
};

module.exports = sendEmail;
            

Code Explanation

Here’s a breakdown of the main parts of the code:

  • Nodemailer setup: We create a transporter using the SMTP configuration.
  • Environment variables: The email and password are stored in the `.env` file for security purposes.
  • Mail options: We define the `from`, `to`, `subject`, and `text` fields that specify how the email will appear to the user.
  • Sending the email: Finally, the `sendMail` function sends the email with the given options.

Tips of the Day

It is essential to store sensitive data, like email credentials, in environment variables (`.env`) to ensure security. Storing them directly in the code may expose them to potential threats. The `nodemailer.js` file is stored in the services folder because it represents a service function, separating it from other application logic like controllers or middleware.

GitHub LinkedIn Live Preview

Post a Comment

0Comments
Post a Comment (0)
To Top