Sending Email Verification with Node.js: A Beginner's Guide

Sending Email Verification with Node.js: A Beginner's Guide

Introduction:

Sending email verification is a crucial step in many web applications, ensuring that users' email addresses are valid and helping to secure their accounts. In this guide, we'll walk through the process of sending email verification using Node.js, a popular JavaScript runtime, Nodemailer for email sending, and the dns package to check network availability.

Getting Started:

Before we dive into the code, let's make sure we have everything set up. You'll need to have Node.js installed on your machine. If you haven't already, you can download and install it from the official Node.js website.

Setting up Nodemailer and DNS:

We'll need to install both Nodemailer and the dns package in our project. Open your terminal or command prompt and navigate to your project directory. Then, run the following commands:

npm install nodemailer
npm install dns

These commands will install Nodemailer and the dns package and add them to your project's dependencies.

Setting up dotenv:

Use this article to setting up dotenv :- How do I setup the dotenv file in Node.js?

Creating the Email Verification Function:

Now that we have Nodemailer and the dns package installed, let's create a function that sends email verification codes to users. We'll start by importing the necessary modules and defining a function called sendVerificationCodeOnMail.

import nodemailer from "nodemailer";
import dns from "dns";

// Function to check network availability
const isNetworkAvailable = async () => {
  return new Promise((resolve) => {
    dns.lookup("smtp.gmail.com", (err) => {
      if (err && err.code === "ENOTFOUND") {
        resolve(false);
      } else {
        resolve(true);
      }
    });
  });
};

// Creating a Nodemailer transporter
const transporter = nodemailer.createTransport({
  host: `smtp.gmail.com`,
  service: "gmail",
  port: 465,
  secure: true,
  auth: {
    user: process.env.SEND_MAIL_NAME, // Your email address
    pass: process.env.SEND_MAIL_PASSWORD, // Your email password or app password
  },
});

// Function to send verification code via email
const sendVerificationCodeOnMail = async ({ email, code }) => {
  try {
    console.log("Sending verification code to:", email);
    // Checking network availability
    if (!(await isNetworkAvailable())) {
      throw new Error("Network is not available");
    }

    // Email options
    const mailOptions = {
      from: process.env.SEND_MAIL_NAME,
      to: email,
      subject: "Welcome to CodeComponents, Confirm Your Signup with OTP",
      html: `
          <!-- Email content -->
      `,
    };

    // Sending email
    const info = await transporter.sendMail(mailOptions);
    console.log("Verification email sent successfully to:", email);
    return true;
  } catch (error) {
    console.error(
      `Error sending verification code to: ${email} - ${error.message}`
    );
    return false;
  }
};

export { sendVerificationCodeOnMail };

Explanation:

  • We import the nodemailer and dns modules to handle email sending and DNS lookups, respectively.

  • The isNetworkAvailable function checks if the network is available by performing a DNS lookup on smtp.gmail.com.

  • We create a Nodemailer transporter, specifying the SMTP configuration required to send emails via Gmail.

  • The sendVerificationCodeOnMail function takes an email address and a verification code as parameters. It checks network availability and sends an email with the verification code.

Git hub link:- github.com/MritunjayKumar07/sendMail