Skip to the content.

<< Go To Home

Introduction to Sending Emails with Nodemailer and Gmail

Nodemailer is a popular Node.js module for sending emails. When combined with Gmail, it requires OAuth2 authentication to ensure secure access.


Step 1: Setting Up OAuth2

To use Gmail’s SMTP server with OAuth2, you need to configure an OAuth2 client in Google Cloud.

1. Create a Google Cloud Project

2. Generate OAuth2 Credentials

3. Generate a Refresh Token


Step 2: Install Dependencies

Run the following command to install the required libraries:

npm install nodemailer googleapis

Step 3: Code Walkthrough

Here’s the full code explained step by step:


1. Import Required Libraries

import nodemailer from 'nodemailer';
import { google } from 'googleapis';
import { error } from 'console';

2. OAuth2 Configuration

const CLIENT_ID = 'your-client-id';
const CLIENT_SECRET = 'your-client-secret';
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const REFRESH_TOKEN = 'your-refresh-token';
const EMAIL_ID = 'your-email@gmail.com';

// Create an OAuth2 client
const oauth2Client = new google.auth.OAuth2(
  CLIENT_ID,
  CLIENT_SECRET,
  REDIRECT_URI
);

oauth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

3. Define the sendGmail Function

interface EmailOptions {
  fromEmail: string;
  toEmail: string;
  subject: string;
  textContent?: string;
  htmlContent?: string;
}

export async function sendGmail(options: EmailOptions) {
  const { toEmail, fromEmail, subject, textContent, htmlContent } = options;

4. Get an Access Token

  try {
    const accessToken = await oauth2Client.getAccessToken();
    if (!accessToken.token) {
      throw error("Couldn't get an access token");
    }

5. Configure Nodemailer Transport

    let transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
        type: 'OAuth2',
        user: EMAIL_ID,
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        refreshToken: REFRESH_TOKEN,
        accessToken: `${accessToken.token}`,
      },
    });

6. Create Mail Options

    const mailOptions = {
      from: fromEmail,
      to: toEmail,
      subject,
      text: textContent,
      html: htmlContent,
    };

7. Send the Email

    const result = await transporter.sendMail(mailOptions);
    console.log('Email sent successfully:', result);
  } catch (error) {
    console.error('Error sending email:', error);
    throw error;
  }
}

Step 4: Common Issues and Fixes

  1. redirect_uri_mismatch Error :
  1. invalid_grant Error :
  1. 403: access_denied Error :
  1. EAUTH Authentication Error :

Step 5: Usage

Here’s an example of calling the sendGmail function:

import { sendGmail } from './emailService';

const emailOptions = {
  fromEmail: 'your-email@gmail.com',
  toEmail: 'recipient-email@gmail.com',
  subject: 'Test Email',
  textContent: 'Hello, this is a test email sent from Node.js!',
  htmlContent: '<p>Hello, this is a <b>test email</b> sent from Node.js!</p>',
};

sendGmail(emailOptions)
  .then(() => console.log('Email sent successfully'))
  .catch((err) => console.error('Error:', err));

Conclusion

This setup allows you to send emails securely using Nodemailer with Gmail and OAuth2.