Sending emails programmatically is a critical feature for many web applications, such as user authentication, password recovery, and notifications. In this article, you'll learn how to send emails in Node.js using Gmail, Nodemailer, and OAuth2. By leveraging Gmail's secure API and Nodemailer's simplicity, you can build a robust email-sending system. Let’s get started!
Why Use Gmail, Nodemailer, and OAuth2?
Gmail: A reliable and widely-used email service with an API for programmatic email sending.
Nodemailer: A powerful Node.js library that simplifies email sending with support for various email services.
OAuth2: Ensures secure authentication without exposing sensitive credentials, making your app more secure.
Steps to Send Emails in Node.js
Follow these steps to set up and use Gmail, Nodemailer, and OAuth2 for email delivery.
1. Install Dependencies
Start by creating a Node.js project and installing the required packages. Run the following commands:
npm init -y
npm install nodemailer googleapis dotenv
2. Set Up a Google Cloud Project
Go to the Google Cloud Console: Navigate to the Google Cloud Console.
Create a new project: Name your project and note the project ID.
Enable Gmail API: Go to API and Services tab → Enabled API and services. Click on +Enable APIs and Services. Search for "Gmail API" in the API library and enable it for your project. Do not select Gmail postmaster tools API, it is not required for sending mails.
Configure OAuth consent screen:
Go to "OAuth consent screen” tab.
Choose the appropriate screen type:
External: For applications used by external users. (I used this for testing and production)
Internal: For applications used within your organization.(You need to register for Google workspace to use this)
Provide Application Information: Fill in the required details like application name, user support email, and privacy policy URL. You can skip the App domains. Provide developer email address.
In API Scopes you can leave it blank or select from search gmail.send to restrict the scope to sending mail.
In Test users, add email ids you would like to use for sending emails.
Create OAuth credentials:
Go to "Credentials" > "Create Credentials" > "OAuth Client ID."
Choose "Web application".
Authorized JavaScript origins: If applicable, add the URLs of your web application's JavaScript origins (e.g.,
http://localhost:5500
).Set the authorized redirect URI to
https://developers.google.com/oauthplayground
and save.You can go to the Credentials tab anytime to download or copy the client id and client secret.
Generate a Refresh Token
Visit the OAuth2 Playground ( developers.google.com/oauthplayground )
From the left pane, under select and authorize APIs, scroll down to go to Gmail API v1. Select mail.google.com and googleapis.com/auth/gmail.send
From the right side, select settings icon (gear icon). Keep other values as it is. Check mark
Use your own OAuth credentials
. Paste the OAuth Client ID: and OAuth Client secret: from the credentials screen created in step 5.Click Authorize APIs.
A consent screen with your app name will open up. Select your mail id that you have provided for testing. Check Send email on your behalf then continue.
Now you will get authorization code.
Exchange the authorization code for refresh token.
You can click on Exchange authorization code for tokens tab and copy the refresh token and add it to your .env file.
Configure the Environment File.
In your project directory, create a .env file
CLIENT_ID=your_client_id_here CLIENT_SECRET=your_client_secret_here REDIRECT_URI=https://developers.google.com/oauthplayground REFRESH_TOKEN=your_refresh_token_here EMAIL=your_email@gmail.com
Write the Email-Sending Code
Here’s the complete script to send an email using Nodemailer and OAuth2. I have used JS module type. You can change import to require for Common JS module.import { google } from "googleapis"; import nodemailer from "nodemailer"; import dotenv from "dotenv"; dotenv.config(); const CLIENT_ID = process.env.CLIENT_ID; const CLIENT_SECRET = process.env.CLIENT_SECRET; const REDIRECT_URI = process.env.REDIRECT_URI; const REFRESH_TOKEN = process.env.REFRESH_TOKEN; const SENDER = process.env.SENDER_EMAIL; const oAuth2Client = new google.auth.OAuth2( CLIENT_ID, CLIENT_SECRET, REDIRECT_URI ); oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN }); async function sendEmail(to, subject, text, html) { try { const accessToken = await oAuth2Client.getAccessToken(); const transporter = nodemailer.createTransport({ service: "gmail", auth: { type: "OAuth2", user: SENDER, clientId: CLIENT_ID, clientSecret: CLIENT_SECRET, refreshToken: REFRESH_TOKEN, accessToken: accessToken.token, }, }); const mailOptions = { from: SENDER, to, subject, text, html, }; const result = await transporter.sendMail(mailOptions); console.log("Email sent successfully:", result); } catch (error) { console.error("Error sending email:", error); } } await sendEmail( "<to email id>", //add actual sent mail id "Register success", "User signup successful", "<h1>User signup successful</h1>" );
Check your email for confirmation.
Conclusion
By following the steps in this guide, you can efficiently send emails in Node.js using Gmail, Nodemailer, and OAuth2. This setup is secure, scalable, and perfect for modern web applications. Start integrating email functionality today to enhance user experience in your app.
If you found this guide helpful, share it with your developer community!