How to Send Emails in Node.js With Nodemailer? [Source Code + GitHub]

By Atit Purani

June 27, 2025

Want to send emails in Node.js without the headache?

Whether you’re building a user registration system, password reset workflow, or marketing tool, email automation is a must-have feature for any modern app.

In this blog, we’ll walk you through a complete Node.js email sending tutorial using Nodemailer, one of the most trusted libraries for email integration.

It’s lightweight, fast, and built specifically for Node.js apps.

Here you’ll learn how to: Send emails in Node.js using SMTP, Add support for HTML, attachments, and Handle errors, and secure your credentials.

If you are looking to send email with nodemailer or trying to use nodemailer npm in your app this blog is perfect for you.

What Is Nodemailer and Why Use It?

Nodemailer is a module for Node.js applications that lets you send emails easily and reliably. It supports a wide range of features like:

  • SMTP setup with authentication
  • Sending HTML emails and plain text
  • Adding attachments
  • OAuth2 integration for secure authentication

It’s trusted by thousands of developers and businesses worldwide. Here are just a few use cases where the Nodemailer SMTP setup comes in handy:

  • Welcome emails after user signup
  • OTP (One-Time Password) systems for login
  • Newsletters and promotional campaigns
  • Contact forms or automated support replies

If you’ve been searching for a nodejs sendmail nodemailer example that works, you’ve just found the right place.

What Do You Need Before Sending Emails in Node.js?

Before we jump into the code, make sure you have the following ready:

  • Node.js and npm are installed on your system.
  • A basic understanding of JavaScript and Express.js.
  • SMTP credentials from an email provider like: Gmail (with app password or OAuth2), Mailtrap (for safe local testing), SendGrid, Outlook, or any SMTP-compatible service

How to Setup Nodemailer in NodeJs to Send Emails?

Let’s start by creating a new project and installing the required packages:

Step 1: Initialize Your Project

          
          mkdir node-email-sender
          cd node-email-sender
          npm init -y
          

Step 2: Install Dependencies

          
          npm install nodemailer dotenv
          

We’ll use:

  • nodemailer for sending emails
  • dotenv to securely store SMTP credentials

Step-by-Step Guide for Sending Emails in Node.Js with Nodemailer

Node-Js-with-Nodemailer

Let’s explore the core of this Node.js email sending tutorial.

We’ll explain how to set up Nodemailer in Node.js with SMTP, write email-sending logic, send HTML/plain emails, add attachments, and handle errors like a pro.

Step 1: Setting Up Nodemailer Transporter (with SMTP)

First, configure the transporter object. This is where SMTP settings come into play.

          
          // mailer.js
          const nodemailer = require("nodemailer");
          require("dotenv").config();
          
          
          // Set up transporter using SMTP
            const transporter = nodemailer.createTransport({
              host: process.env.SMTP_HOST,
              port: process.env.SMTP_PORT,
              secure: process.env.SMTP_SECURE === "true", // true for 465, false for 587
              auth: {
              user: process.env.SMTP_USER,
              pass: process.env.SMTP_PASS,
              },
            });
            module.exports = transporter;
          

This is how you set up Nodemailer in Node.js with SMTP for sending secure and authenticated emails.

Step 2: Creating the Email Sending Logic

Now let’s write a function to send the email using that transporter.

          
          // sendMail.js
          const transporter = require("./mailer");
            
            async function sendMail(to, subject, text, html) {
              try {
              const info = await transporter.sendMail({
                from: `"Your Company" <${process.env.SMTP_USER}>`,
                to,
                subject,
                text,
                html,
                attachments: [], // Optional
              });
            
              console.log("Message sent: %s", info.messageId);
              } catch (error) {
              console.error("Error sending email:", error);
              }
            }
            module.exports = sendMail;`
          

Step 3: Sending Plain Text & HTML Emails

You can now send a plain text or HTML email like this:

          
         // index.js
            const sendMail = require("./sendMail");
            
            sendMail(
              "client@example.com",
              "Welcome to Our App",
              "Hello! Thanks for signing up.",
              "<h1>Welcome!>/h1>>p>We’re glad you joined us.>/p>"
            );
          

Step 4: Sending Attachments (Optional)

Add attachments using the attachments field:

          
            // Inside sendMail function
            attachments: [
              {
              filename: "invoice.pdf",
              path: "./files/invoice.pdf", // path to local file
              },
            ],

          

This is helpful for apps that send invoices, reports, or any documents.

Step 5: Error Handling & Logging

You should always wrap your sending logic in try-catch blocks (as shown above). Log errors clearly and handle failures gracefully

You can explore and download the Node.js Nodemailer complete source code [GitHub].

How to Use Environment Variables for Secure Email Config?

Environment-Variables-for-Secure-Email-Config

Never hardcode SMTP credentials in your code. Use .env files with the dotenv package:

Step 1: Install dotenv

          
           npm install dotenv
          

Step 2: Create a .env file

          
           SMTP_HOST=smtp.gmail.com
           SMTP_PORT=587
           SMTP_SECURE=false
           SMTP_USER=your_email@gmail.com
           SMTP_PASS=your_app_password
          

Step 3: Load in your code

          
           require("dotenv").config();
          

Best Practices:

  • Never push .env to GitHub, add it to .gitignore
  • Rotate passwords regularly
  • Use app-specific passwords or OAuth2 when possible

How to Add a Frontend Email Form? (Optional)

Want to let users send emails from your app? Add a simple HTML form that talks to your backend.

Example HTML Form

          
           <form action="/send-email" method="POST">
            <input type="email" name="to" placeholder="Recipient Email" required />
            <input type="text" name="subject" placeholder="Subject" required />
            <textarea name="message" placeholder="Your message" required></textarea>
            <button type="submit">Send Email</button>
          </form>
          

Example Express Route

          
          // server.js
          const express = require("express");
          const bodyParser = require("body-parser");
          const sendMail = require("./sendMail");
          
          const app = express();
          app.use(bodyParser.urlencoded({ extended: false }));
          
          app.post("/send-email", async (req, res) =< {
            const { to, subject, message } = req.body;
            await sendMail(to, subject, message, `
${message}

`); res.send("Email sent successfully!"); }); app.listen(3000, () =< console.log("Server started on http://localhost:3000"));

How Seven Square Can Help in NodeJs Email Integration?

At Seven Square, we’ve helped startups, SaaS platforms, and enterprises to integrate email features using technologies like Node.js, Express, and Nodemailer securely.

We don’t just write code, we build production-ready, tested, and secure email solutions that deliver value to your users and business.

  • Custom Email Logic using Nodemailer, tailored to your business use case (e.g., registration, invoices, OTP).
  • Secure SMTP Configuration with Gmail, Mailtrap, SendGrid, and more.
  • HTML Template Support for branded emails, marketing newsletters, and notifications.
  • Attachment Support for receipts, reports, invoices, and dynamic PDFs.
  • API Integration for frontend forms, user events, and workflows.
  • Environment Configuration to protect sensitive credentials with .env and secure deployment practices.
  • Testing & Error Handling to ensure high deliverability and uptime.

Want to Build a NodeJs app? Contact Us Now!

FAQs

  • Nodemailer is a powerful Node.js library that allows you to send emails via SMTP, Gmail, SendGrid, and other providers.
  • It supports HTML templates, attachments, OAuth2, and is easy to integrate into Node.js apps & make it the go-to solution for any Node.js email integration.

  • Yes, Nodemailer allows you to send both plain text and rich HTML emails.
  • You simply pass the text and/or html fields when calling sendMail() to support different email clients.

  • You can use Gmail, Outlook, Mailtrap, Yahoo, Zoho, or any provider that supports SMTP.
  • Services like Mailtrap are great for testing, while Gmail and SendGrid are popular for production.

  • Use Mailtrap for safe local email testing.
  • It simulates inboxes without sending real emails, helping you test your Node.js Nodemailer email code without affecting real users.

Get in Touch

Got a project idea? Let's discuss it over a cup of coffee.

    Get in Touch

    Got a project idea? Let's discuss it over a cup of coffee.

      COLLABORATION

      Got a project? Let’s talk.

      We’re a team of creative tech-enthus who are always ready to help business to unlock their digital potential. Contact us for more information.