Send Email - Nodemailer

Documentation: Sending Email with Nodemailer

Overview

Nodemailer is a module for Node.js applications to allow easy as cake email sending. This documentation will guide you through the basics of setting up and using Nodemailer to send an OTP (One-Time Password) via email.


Prerequisites

  • Node.js installed on your system.

  • A Gmail account for sending emails.

  • Basic knowledge of JavaScript and Node.js.


Installation

First, you need to install Nodemailer. You can do this using npm (Node Package Manager):

npm install nodemailer

Environment Setup

Create a .env file in the root of your project to store sensitive information such as your email and password.

PORTAL_EMAIL=your-email@gmail.com
PORTAL_PASSWORD=your-email-password

Make sure to add .env to your .gitignore file to prevent it from being committed to your version control system.


Sending an Email with Nodemailer

Here is a step-by-step guide to setting up and using Nodemailer to send an OTP email.

1. Importing Nodemailer

First, import Nodemailer into your project:

import nodemailer from 'nodemailer';

2. Configuring Nodemailer

Set up the email configuration, specifying the service and authentication details. This example uses Gmail, but Nodemailer supports various email services.

const emailConfig = {
    service: 'gmail',
    auth: {
        user: process.env.PORTAL_EMAIL,
        pass: process.env.PORTAL_PASSWORD,
    },
};

3. Creating the Email Sending Function

Create a function to send an OTP via email. This function takes the recipient's email address and the OTP as parameters.

async function sendEmailOTP(mail, otp) {
    const transporter = nodemailer.createTransport(emailConfig);

    const mailOptions = {
        from: process.env.PORTAL_EMAIL,
        to: mail,
        subject: 'OTP Verification',
        text: `Your OTP is: ${otp}`,
    };

    try {
        await transporter.sendMail(mailOptions);
        return `OTP sent to ${mail} via email`;
    } catch (error) {
        throw `Error sending OTP to ${mail} via email: ${error}`;
    }
}

export { sendEmailOTP };

4. Using the Function

To use the sendEmailOTP function, you need to call it with the recipient's email address and the OTP. Here's an example of how to do this:

import { sendEmailOTP } from './path-to-your-file';

// Example usage
const recipientEmail = 'recipient@example.com';
const otp = '123456';

sendEmailOTP(recipientEmail, otp)
    .then(response => console.log(response))
    .catch(error => console.error(error));

Full Code Example

Here is the complete code, including the import statement, email configuration, and function definition:

import nodemailer from 'nodemailer';
import dotenv from 'dotenv';

dotenv.config(); // To load the environment variables from .env file

const emailConfig = {
    service: 'gmail',
    auth: {
        user: process.env.PORTAL_EMAIL,
        pass: process.env.PORTAL_PASSWORD,
    },
};

async function sendEmailOTP(mail, otp) {
    const transporter = nodemailer.createTransport(emailConfig);

    const mailOptions = {
        from: process.env.PORTAL_EMAIL,
        to: mail,
        subject: 'OTP Verification',
        text: `Your OTP is: ${otp}`,
    };

    try {
        await transporter.sendMail(mailOptions);
        return `OTP sent to ${mail} via email`;
    } catch (error) {
        throw `Error sending OTP to ${mail} via email: ${error}`;
    }
}

export { sendEmailOTP };

// Example usage
const recipientEmail = 'recipient@example.com';
const otp = '123456';

sendEmailOTP(recipientEmail, otp)
    .then(response => console.log(response))
    .catch(error => console.error(error));

Error Handling

When using the sendEmailOTP function, it’s important to handle errors appropriately. The function will throw an error if it encounters any issues while sending the email. Ensure that you catch and handle these errors in your application to avoid crashes and provide feedback to the user.


Conclusion

This documentation covers the basics of sending an email using Nodemailer. By following these steps, you should be able to set up and use Nodemailer to send OTP emails or any other types of emails in your Node.js applications. Remember to keep your email credentials secure and not hard-code them into your application.

Instructor: Muhammad Sufiyan

Linkedin: linkedin.com/in/innosufiyan