Node.js & Express

Sending Emails with Node.js

15 min Lesson 20 of 40

Introduction to Email Sending

Sending emails is a critical feature in most web applications for user verification, password resets, notifications, newsletters, and transactional messages. Node.js provides robust libraries for integrating email functionality into your applications.

Email Use Cases: Welcome emails, email verification, password reset, order confirmations, invoice delivery, notification alerts, marketing campaigns, and automated reports.

Installing Nodemailer

Nodemailer is the most popular Node.js module for sending emails with support for multiple transport methods:

# Install Nodemailer
npm install nodemailer

# Install dotenv for environment variables
npm install dotenv
Gmail Setup: For Gmail, enable "Less secure app access" or use an App Password (recommended). Visit Google Account settings → Security → 2-Step Verification → App Passwords to generate a password for your application.
Production Best Practices: Use environment variables for credentials. Implement rate limiting to avoid being marked as spam. Always include unsubscribe links in marketing emails. Use queue systems for high-volume sending. Monitor email delivery rates and bounce metrics.

Practice Exercise

  1. Set up Nodemailer with SMTP configuration using Gmail
  2. Create email service functions:
    • Send welcome email (HTML with template)
    • Send password reset email with token
    • Send order confirmation with invoice attachment
  3. Implement email templates using Handlebars
  4. Add email queue using Bull for background processing
  5. Create API endpoints:
    • POST /api/auth/forgot-password - Queue password reset email
    • POST /api/orders/:id/send-invoice - Send order invoice
  6. Test all email functions and verify delivery
  7. Optional: Integrate SendGrid or Mailgun for production use