Paramclasses Academy - Blog

Tutorials Details

←
Post 31 of 40
→

Send Emails from Node.js Using SMTP and Nodemailer: Complete Practical Tutorial

Send Emails from Node.js Using SMTP and Nodemailer: Complete Practical Tutorial

October 30, 2026

✦ Send Emails from Node.js Using SMTP and Nodemailer: Complete Practical Tutorial

Email communication is an important feature of modern web applications. Websites send emails for user registration, account verification, password reset, order confirmation, appointment reminders, and contact form notifications.

If you are developing a school management system, hospital management system, e-commerce website, or CRM application, you may need to send automatic emails from your Node.js backend.

Node.js makes email integration easy with a popular package called Nodemailer. It allows developers to send emails through SMTP servers and supported email services.

In this practical tutorial, you will learn how to configure Nodemailer, connect it to an SMTP server, send text and HTML emails, and build a working email API using Node.js and Express.js.

✦ What Is Nodemailer in Node.js?

Nodemailer is a Node.js module used to send emails from server-side applications.

It supports different email transport methods, including SMTP. SMTP stands for Simple Mail Transfer Protocol. It is a standard protocol used to send emails between mail servers.

Using Nodemailer, you can send:

  • Plain text emails.

  • HTML emails.

  • Registration confirmation emails.

  • Password reset notifications.

  • Order confirmation emails.

  • Emails with attachments.

✦ What Is SMTP?

SMTP stands for Simple Mail Transfer Protocol. It is used to send outgoing emails from an application to an email server.

For example, when a user submits a contact form on your website, your Node.js application can use SMTP to send the submitted message to your business email address.

Common SMTP providers include:

  • Gmail SMTP.

  • Outlook SMTP.

  • Custom domain email SMTP.

  • Hosting provider SMTP.

  • Transactional email services.

For this tutorial, we will use Gmail SMTP as an example.

✦ How Email Sending Works in Node.js

The basic process is:

  1. A user submits a form or performs an action.

  2. The Node.js server receives the request.

  3. Express.js validates the submitted information.

  4. Nodemailer connects to the configured SMTP server.

  5. The SMTP server processes the outgoing email.

  6. Nodemailer returns the result to the application.

  7. The application sends a response to the client.

✦ Step 1: Create a Node.js Project

Create a project folder:

mkdir nodejs-email
cd nodejs-email
npm init -y

Install the required packages:

npm install express nodemailer dotenv

We will use:

  • Node.js – JavaScript runtime.

  • Express.js – API development.

  • Nodemailer – sending emails.

  • dotenv – managing environment variables.

Our project structure will look like this:

nodejs-email/
│
├── config/
│   └── mail.js
│
├── .env
├── .gitignore
├── server.js
└── package.json

✦ Step 2: Configure Gmail SMTP

Before connecting Gmail with Node.js, you need to prepare your Google account.

For Gmail SMTP using an App Password:

  1. Open your Google Account settings.

  2. Enable 2-Step Verification if it is not already enabled.

  3. Open the App Passwords section, if your account supports it.

  4. Generate an App Password for your application.

  5. Use that App Password in your Node.js environment configuration.

An App Password is different from your normal Gmail account password.

Important: Do not place your Gmail password or App Password directly inside your JavaScript code. Store credentials in environment variables and keep them private.

✦ Step 3: Create the .env File

Create a .env file in your project root:

PORT=3000

SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_SECURE=true

SMTP_USER=your-email@gmail.com
SMTP_PASS=your-16-character-app-password

MAIL_FROM=your-email@gmail.com
MAIL_TO=receiver@example.com

Replace the example values with your actual email configuration.

For Gmail:

  • Port 465 uses secure SMTP.

  • Port 587 generally uses STARTTLS.

  • SMTP_SECURE=true is used with port 465.

  • For port 587, use SMTP_SECURE=false so the connection can upgrade using STARTTLS.

Create a .gitignore file:

node_modules/
.env

This prevents your private SMTP credentials from being committed to a Git repository.

✦ Step 4: Create the Nodemailer Configuration

Create a folder named config and add mail.js:

const nodemailer = require("nodemailer");

const transporter = nodemailer.createTransport({

    host: process.env.SMTP_HOST,

    port: Number(process.env.SMTP_PORT),

    secure: process.env.SMTP_SECURE === "true",

    auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS
    }

});

module.exports = transporter;

Understanding the code:

  • createTransport() creates the email transport.

  • host specifies the SMTP server.

  • port specifies the SMTP port.

  • secure controls whether the connection starts with TLS.

  • auth contains your SMTP username and password.

We export the transporter so that other files can use it.

✦ Step 5: Verify SMTP Connection

Before sending emails, it is useful to check whether your SMTP configuration works.

Add the following code in server.js after loading the transporter:

transporter.verify((error, success) => {

    if (error) {

        console.log("SMTP connection failed:", error.message);

    } else {

        console.log("SMTP server is ready to send emails");

    }

});

The verify() method checks the SMTP connection and authentication settings.

It does not send an actual email.

✦ Step 6: Send Your First Email

Now create server.js:

require("dotenv").config();

const express = require("express");

const transporter = require("./config/mail");

const app = express();

app.use(express.json());


// Test Email API
app.get("/send-email", async (req, res) => {

    try {

        const info = await transporter.sendMail({

            from: process.env.MAIL_FROM,

            to: process.env.MAIL_TO,

            subject: "My First Email from Node.js",

            text: "Hello! This email was sent using Node.js and Nodemailer."

        });

        res.json({

            message: "Email sent successfully",

            messageId: info.messageId

        });

    } catch (error) {

        console.error("Email error:", error);

        res.status(500).json({

            message: "Unable to send email"

        });

    }

});


// Start Server
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {

    console.log(`Server running at http://localhost:${PORT}`);

});

Start the application:

node server.js

Open this URL in your browser:

http://localhost:3000/send-email

If your SMTP settings are correct, Nodemailer will send an email to the configured recipient.

✦ Step 7: Send an HTML Email

Plain text emails are useful, but professional applications often need formatted HTML emails.

Nodemailer supports HTML email content through the html property.

For example:

app.get("/send-html-email", async (req, res) => {

    try {

        await transporter.sendMail({

            from: process.env.MAIL_FROM,

            to: process.env.MAIL_TO,

            subject: "Welcome to Our Website",

            html: `
                <div style="
                    font-family: Arial, sans-serif;
                    padding: 20px;
                    background: #f5f5f5;
                ">

                    <h2 style="color: #1d4ed8;">
                        Welcome!
                    </h2>

                    <p>
                        Thank you for joining our website.
                    </p>

                    <p>
                        We are happy to have you with us.
                    </p>

                    <strong>Team Param Classes</strong>

                </div>
            `

        });

        res.json({
            message: "HTML email sent successfully"
        });

    } catch (error) {

        console.error(error);

        res.status(500).json({
            message: "Email sending failed"
        });

    }

});

The html property allows you to create formatted emails using HTML and inline CSS.

For better compatibility, email designs should use simple HTML and inline styles.

✦ Step 8: Create a Contact Form Email API

Now we will create a practical example.

Suppose a visitor fills out a contact form on your website with:

  • Name.

  • Email.

  • Subject.

  • Message.

Our Node.js API will receive the information and send it to the website owner's email address.

Add this route to server.js:

app.post("/api/contact", async (req, res) => {

    try {

        const {
            name,
            email,
            subject,
            message
        } = req.body;

        // Basic validation
        if (!name || !email || !subject || !message) {

            return res.status(400).json({

                message: "All fields are required"

            });

        }

        // Send contact form email
        await transporter.sendMail({

            from: process.env.MAIL_FROM,

            to: process.env.MAIL_TO,

            replyTo: email,

            subject: `Contact Form: ${subject}`,

            text: `
                Name: ${name}
                Email: ${email}
                Subject: ${subject}
                Message: ${message}
            `

        });

        res.json({

            message: "Your message has been sent successfully"

        });

    } catch (error) {

        console.error("Contact email error:", error);

        res.status(500).json({

            message: "Unable to send your message"

        });

    }

});

Here, replyTo allows the website owner to reply to the visitor's email address.

The sender remains your authenticated SMTP account, which is better than pretending that the visitor's email address is your own sender address.

For a production contact form, also validate email format and limit request frequency to prevent spam.

✦ Step 9: Test the Contact API Using Postman

Open Postman and create a POST request:

http://localhost:3000/api/contact

Select Body → raw → JSON.

Enter:

{
    "name": "Rahul Sharma",
    "email": "rahul@example.com",
    "subject": "Website Development",
    "message": "I want to know more about your website development services."
}

Click Send.

A successful response will look like:

{
    "message": "Your message has been sent successfully"
}

Check the configured recipient inbox to confirm that the message arrived.

✦ Step 10: Send Email Attachments

Nodemailer also supports attachments.

For example, you can attach a PDF invoice or document:

await transporter.sendMail({

    from: process.env.MAIL_FROM,

    to: process.env.MAIL_TO,

    subject: "Your Invoice",

    text: "Please find your invoice attached.",

    attachments: [
        {
            filename: "invoice.pdf",
            path: "./invoice.pdf"
        }
    ]

});

The filename property defines the attachment name shown to the recipient.

The path property specifies the location of the file on your server.

Only attach files that your application is authorized to share, and validate file paths carefully.

✦ Common Nodemailer Errors and Solutions

1. Invalid Login

Your SMTP username or password may be incorrect. Check your SMTP credentials and App Password.

2. Connection Timeout

Check your internet connection, SMTP host, port, and hosting provider's outbound SMTP restrictions.

3. Authentication Failed

Make sure your account supports the selected authentication method. For Gmail, check 2-Step Verification and App Password availability.

4. Email Not Received

Check the recipient address, spam folder, SMTP response, and your email provider's sending limits.

5. TLS or SSL Error

Check that your SMTP port and secure setting match the provider's configuration.

✦ Important Email Security Best Practices

Follow these practices when sending emails from a real-world Node.js application:

  1. Never hardcode SMTP passwords in source code.

  2. Use environment variables or a secure secrets manager.

  3. Validate user-submitted email addresses.

  4. Do not allow users to control arbitrary email headers.

  5. Add rate limiting to public email APIs.

  6. Avoid exposing SMTP error details to clients.

  7. Use trusted SMTP or transactional email providers.

  8. Configure SPF, DKIM, and DMARC for your sending domain.

  9. Avoid sending passwords or sensitive information in plain text.

  10. Use email templates for consistent and maintainable messages.

✦ Frequently Asked Questions

Q1. What is Nodemailer in Node.js?

Nodemailer is a Node.js package used to send emails through SMTP and supported email transport services.

Q2. Can Node.js send emails using Gmail?

Yes. Node.js can send emails using Gmail SMTP when the account and authentication method are configured correctly.

Q3. What is SMTP in Node.js?

SMTP is the protocol used by an application to send outgoing emails through a mail server.

Q4. Can Nodemailer send HTML emails?

Yes. You can use the html property in sendMail() to send formatted HTML email content.

Q5. Can Nodemailer send PDF attachments?

Yes. Nodemailer supports attachments using the attachments option.

✦ Conclusion

Sending emails is an important feature of backend application development. With Node.js and Nodemailer, developers can easily integrate email functionality into websites and applications.

In this tutorial, we learned how to configure Gmail SMTP, create a Nodemailer transporter, send plain text and HTML emails, build a contact form API, and attach PDF documents.

You can use these concepts to build registration confirmation emails, password reset notifications, order alerts, and automated email systems.

Learn practical Node.js, Express.js, MySQL, REST API Development, and Backend Programming with Param Classes.

←
Post 31 of 40
→