Sending email with Nodemailer and OAuth 2.0
March 4, 2025
5 min read
Preview

Email sending feature is a-must in almost every application. Here is the tutorial on how we can send email using nodemailer and OAuth 2.0 🚀🔥 

This first step is crucial as we need client ID and client secret which will be later added in the OAuth2 playground to enable mail. First, we need to sign-in to google cloud console. If you have not created a project there, you need to create one and also set up a consent screen. 

For now, I’m assuming we already have that. On the side menu, go to the “APIs and services” menu and click on “Credentials”. After that click on “CREATE CREDENTIALS” in the top-middle section. A dropdown menu will appear. From there, click on OAuth client ID. After that, select the application type you need (for now: Web application) and fill up the name you want. For “Authorised redirect URIs”, add this URI: https://developers.google.com/oauthplayground. This URI is of OAuth 2.0 playground. Now click on “CREATE”.

 

 


Note: the created project might take a few minutes to hours to come into effect.

 

Right after creating, we will get client ID and client secret. Now go to OAuth 2.0 playground.   



On the right top, click on the setting icon. There we will see different options but one we need appears after checking on “Use your own OAuth credentials”. After checking, input fields with client ID and client secret appear. Paste those credentials we got from google console and close it. After that on the right panel in “Step 1”, search for “Gmail API v1” and click on “https://mail.google.com/”. Click on the “Authorize APIs” button.

After success, Step 2 will be active and we can see the Authorization code and exchange button just below it. Click on the button. Now we will get “Refresh token” and “Access token”.

Okay now let’s do some coding 👨‍💻

  1. Create a project
    Go to your preferred terminal and run:

    npm init -y


    This command will initialize your node project and create package.json for you.
    Install necessary packages: 

    npm install nodemailer googleapis


    "googleapis" package is required to authenticate and authorize.

  2. Create env file and paste the credentials like following:

    GOOGLE_PLAYGROUND_REFRESH_TOKEN=<your refresh token>
    GOOGLE_APP_CLIENT_ID=<your client id>
    GOOGLE_APP_CLIENT_SECRET=<your client secret>
    GOOGLE_PLAYGROUND_REDIRECT_URI=https://developers.google.com/oauthplayground
    

     

  3. For better read, I’ve created a config file:

    // config.js in root directory
    
    require("dotenv").config();
    
    const GOOGLE_PLAYGROUND_REFRESH_TOKEN =
      process.env.GOOGLE_PLAYGROUND_REFRESH_TOKEN;
    const GOOGLE_APP_CLIENT_ID = process.env.GOOGLE_APP_CLIENT_ID;
    const GOOGLE_APP_CLIENT_SECRET = process.env.GOOGLE_APP_CLIENT_SECRET;
    
    module.exports = {
      GOOGLE_PLAYGROUND_REFRESH_TOKEN,
      GOOGLE_APP_CLIENT_ID,
      GOOGLE_APP_CLIENT_SECRET,
    };
    

     

  4. Next, I’m creating a src/service directory and new file inside service directory
    From root directory, run the following commands:

    mkdir -p src/service
    touch src/service/nodemailer.js

     

  5. Open the nodemailer.js file and paste the following code:

    const nodemailer = require("nodemailer");
    const { google } = require("googleapis");
    
    const {
      GOOGLE_PLAYGROUND_REDIRECT_URI,
      GOOGLE_APP_CLIENT_ID,
      GOOGLE_APP_CLIENT_SECRET,
      GOOGLE_PLAYGROUND_REFRESH_TOKEN,
    } = require("../config");
    
    async function initiateTransporter(user) {
      try {
        const oAuth2client = new google.auth.OAuth2(
          GOOGLE_APP_CLIENT_ID,
          GOOGLE_APP_CLIENT_SECRET,
          GOOGLE_PLAYGROUND_REDIRECT_URI
        );
        oAuth2client.setCredentials({
          refresh_token: GOOGLE_PLAYGROUND_REFRESH_TOKEN,
        });
    
        const transporter = nodemailer.createTransport({
          service: "gmail",
          auth: {
            type: "OAuth2",
            user,
            clientId: GOOGLE_APP_CLIENT_ID,
            clientSecret: GOOGLE_APP_CLIENT_SECRET,
            refreshToken: GOOGLE_PLAYGROUND_REFRESH_TOKEN,
          },
        });
    
        return transporter;
      } catch (err) {
        console.log("Error while initiating transporter");
        console.log(err);
      }
    }
    
    module.exports = { initiateTransporter };
    


    As you can see here, this code simply authenticates and establishes a connection using googleapis. After that there is the invoke of createTransport() function provided by nodemailer.

  6. Now create another file or function whose main purpose is to send email. Here I’ve created an email.js file at the root directory.

    const { initiateTransporter } = require("./service/nodemailer");
    
    async function emailInitiate() {
      try {
        const yourEmail = "<Your email address>";
        const transporter = await initiateTransporter(yourEmail);
    
        await transporter.sendMail({
          from: yourEmail,
          to: "<Email address to whom you want to send email>",
          subject: "Nodemailer with OAuth",
          html: "<p>Hello world</p>",
          attachments: [], // include if any
        });
    
        console.log("Email sent");
      } catch (err) {
        console.log("Error while sending email");
      }
    }
    
    emailInitiate();

     

  7. Now lets run following in your terminal:

    node src/email.js


    Output will be displayed after email is sent successfully:

    Email sent


    Happy coding!! 🙂

© 2025 Sandeep Bajracharya