Vanguardbytes SALE Website 97.82% DISCOUNTED PROMO OFFER »

· Admin · Software Development  · 4 min read

How to Send Emails with Node.js Using SMTP, Gmail, and OAuth2

A guide on implementing an email system in a Node.js application using SMTP, Gmail, and OAuth2 for authentication.

A guide on implementing an email system in a Node.js application using SMTP, Gmail, and OAuth2 for authentication.

Explore the process of sending emails using Node.js, SMTP, Gmail, and OAuth2. This involves using Nodemailer, a module for Node.js applications, for sending emails, and OAuth2 for Gmail authentication. This guide provides detailed instructions on setting up Nodemailer with Gmail using OAuth2.

To set up Nodemailer with Gmail using OAuth2, you need to follow these steps:

  1. Create a project in the Google Cloud Console:
  • Go to the Google Cloud Console.
  • Click on “Select a project” > “NEW PROJECT”, and follow the steps to create a new project. Google Cloud Console New Project Image

Select the Project Image

  1. Enable the Gmail API:
  • In your project dashboard, navigate to “Dashboard” > “APIs & Services”. API and Services Image

  • Click ”+ ENABLE APIS AND SERVICES”. Enable APIs and Services Image

  • Search and click for “Gmail API”. Gmail API Image

  • Enable Gmail API for your project. Enable Gmail API for your project Image

  1. Create credentials:
  • Go to “APIs & Services” > “Credentials”. Go to APIs & Services to Credentials Image

  • Click “Create Credentials” > “OAuth client ID”. Click Create Credentials to OAuth client ID Image

  • If prompted, configure the consent screen by clicking “CONFIGURE CONSENT SCREEN” and follow the steps. You’ll need to set it to “External” and fill out the required fields. Configure Consent Screen Image

  • Add a scope of the application, and select “https://www.mail.google.comAdding scope mail google to application Image

  • Once the consent screen is configured, return to “Create credentials” > “OAuth client ID”.

  • For “Application type”, select “Web application”.

  • Add a name for your OAuth 2.0 client. Select Web Application Image

  • Under “Authorized redirect URIs”, add “http://127.0.0.1:3000/oauth” and “https://developers.google.com/oauthplayground” if you plan to use the OAuth Playground to generate your refresh token.

  • Click “Create”. Create to generate refresh token image

  • Note down or download the “Client ID” and “Client Secret”. Download client ID and client Secret Image

  1. Generate a Refresh Token using the OAuth Playground:
  • Go to the OAuth 2.0 Playground.

  • Click the gear icon in the top right corner, check “Use your own OAuth credentials”, and enter your OAuth Client ID and Client Secret.

  • In the “Select the Scope” box, scroll to “Gmail API v1” and select “https://mail.google.com/”, and “https://www.googleapis.com/auth/gmail.send”.

  • Click “Authorize APIs” and follow the steps to authorize your OAuth credentials. Authorize API Image

  • Exchange authorization code for tokens. Exchange Authorization Code Image

  • Copy the “Refresh Token” that is generated. Generated Refresh Tokens Image

  1. Configure Nodemailer with your OAuth2 credentials in your Server.js:
    Replace the placeholders in your Nodemailer configuration with your actual credentials:

To use Nodemailer with OAuth2 in a Node.js project, you need to install the following packages:

(1). nodemailer: This is the main package for sending emails.

(2.) google-auth-library: This package is used for Google’s OAuth2 authentication.

You can install these packages using npm. Here is the command to install these packages:

npm install --save nodemailer google-auth-library
const { google } = require('google-auth-library');
const nodemailer = require('nodemailer');

// OAuth2 client setup
const CLIENT_ID = "YOUR_CLIENT_ID.apps.googleusercontent.com",
const CLIENT_SECRET = "YOUR_CLIENT_SECRET",
const REDIRECT_URI = 'https://developers.google.com/oauthplayground';
const REFRESH_TOKEN = "YOUR_REFRESH_TOKEN",
const ACCESS_TOKEN = "YOUR_ACCESS_TOKEN",

const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });

app.post('/send-email', async (req, res) => {
  console.log('Received request body:', req.body);
  const { name, email, subject, message } = req.body;
  try {
    const accessToken = await OAuth2Client.getAccessToken();

    const transporter = nodemailer.createTransport({
      host: 'smtp.gmail.com',
      port: 465,
      secure: true,
      auth: {
        type: 'OAuth2',
        user: 'EMAIL_SENDER',
        clientId: CLIENT_ID,
        clientSecret: CLIENT_SECRET,
        refreshToken: REFRESH_TOKEN,
        accessToken: ACCESS_TOKEN,
        //accessToken: accessToken.token,
      },
      tls: {
        rejectUnauthorized: false
      }
    });

    const mailOptions = {
      from: `"${name}" <${email}>`,
      to: 'EMAIL_RECEIVER',
      subject: subject,
      text: `Message from: ${name} <${email}>\n\n${message}`,
    };

    await transporter.sendMail(mailOptions);
    console.log('Email sent successfully');
    res.status(200).send('Email sent successfully');
  } catch (error) {
    console.error('Error sending email:', error);
    res.status(500).send('Error sending email: ' + error.message);
  }
});

Bottleneck

However, there’s a potential problem you might encounter. When we obtain the refresh and access tokens from the Google OAuth 2.0 Playground, they expire after 3600 seconds. This expiration means that we can’t send messages via the Gmail API once the token expires.

To address this issue, we need to manually configure the Google OAuth 2.0 Playground. On the right side of the screen, click the settings icon. Then, in the OAuth Flow, select “Server-side”. In the OAuth Endpoint, select “Custom”. In the Authorization Endpoint, type or paste “https://accounts.google.com/o/oauth2/auth”. In the token endpoint, type or paste “https://oauth2.googleapis.com/token”. In the access token location, select “Authorization Header w/ Bearer prefix”. Finally, in the OAuth Client ID and the OAuth Client Secret fields, type or paste your respective credentials, “YOUR_CLIENT_ID” and “YOUR_CLIENT_SECRET”. This approach effectively resolves the issue of having to refresh the token once it expires.

Manually configured Google Oauth Playground Image

  1. Congratulations!!! You have successfully sent a message via a web form using Gmail SMTP and Nodemailer in Node.js. Contact Form test using Gmail SMPT Gmail SMPT Success Email Sent Feedback to Client Side Image Gmail email sent to the client Image
Back to Blog

Related Posts

View All Posts »