Skip to main content

Command Palette

Search for a command to run...

Send Email - Nodemailer

Published
3 min read
M

As a former 3D Animator with more than 12 years of experience, I have always been fascinated by the intersection of technology and creativity. That's why I recently shifted my career towards MERN stack development and software engineering, where I have been serving since 2021.

With my background in 3D animation, I bring a unique perspective to software development, combining creativity and technical expertise to build innovative and visually engaging applications. I have a passion for learning and staying up-to-date with the latest technologies and best practices, and I enjoy collaborating with cross-functional teams to solve complex problems and create seamless user experiences.

In my current role as a MERN stack developer, I have been responsible for developing and implementing web applications using MongoDB, Express, React, and Node.js. I have also gained experience in Agile development methodologies, version control with Git, and cloud-based deployment using platforms like Heroku and AWS.

I am committed to delivering high-quality work that meets the needs of both clients and end-users, and I am always seeking new challenges and opportunities to grow both personally and professionally.

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: https://www.linkedin.com/in/innosufiyan/