Home Web Front-end JS Tutorial Build a Professional Email Service: Gmail OAuth Express Webhooks

Build a Professional Email Service: Gmail OAuth Express Webhooks

Oct 28, 2024 am 02:47 AM

Email notifications are crucial for modern web applications. In this guide, we'll build a secure email notification service using Express.js and Gmail's OAuth2 authentication. Our service will accept webhook requests and automatically send emails based on the incoming data.

What We're Building

We'll create an Express server that:

  • Receives webhook data via POST requests
  • Authenticates with Gmail using OAuth2
  • Sends customized emails based on the webhook payload
  • Handles errors gracefully

Prerequisites

  • Node.js installed on your machine
  • A Google Cloud Console project with Gmail API enabled
  • OAuth2 credentials (Client ID, Client Secret, Refresh Token)
  • Basic understanding of Express.js and async/await

Project Setup

First, install the required packages:

npm install express body-parser nodemailer googleapis dotenv
Copy after login
Copy after login
Copy after login

Create a .env file with your credentials:

CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
REDIRECT_URI=your_redirect_uri
REFRESH_TOKEN=your_refresh_token
EMAIL_USER=your_email@gmail.com
Copy after login
Copy after login

If you encounter any difficulties setting up these credentials, like I did, you can follow the steps below...

Step-1: Create a new Google Cloud project:

a. Go to https://console.cloud.google.com/
b. Click on the project dropdown at the top of the page
c. Click "New Project"
d. Enter a project name and click "Create"

Build a Professional Email Service: Gmail OAuth Express   Webhooks

Step-2: Enable the Gmail API:
a. In the left sidebar, go to "APIs & Services" > "Library"
b. Search for "Gmail API"
c. Click on "Gmail API" and then click "Enable"

Build a Professional Email Service: Gmail OAuth Express   Webhooks


Step-3: Configure the OAuth consent screen:
a. Go to "APIs & Services" > "OAuth consent screen"
b. Choose "External" as the user type and click "Create"
c. Fill in the required fields:
- App name: [Your app name]
- User support email: [Your email]
- Developer contact information: [Your email]
d. Click "Save and Continue"
e. On the "Scopes" page, click "Add or Remove Scopes"
f. Find and select "https://mail.google.com/" scope
g. Click "Update" and then "Save and Continue"
h. On the "Test users" page, click "Add Users"
i. Add your Gmail address and click "Save and Continue"
j. Review the summary and click "Back to Dashboard"


Step-4: Create OAuth2 credentials:
a. Go to "APIs & Services" > "Credentials"
b. Click "Create Credentials" > "OAuth client ID"
c. Choose "Web application" as the application type
d. Name: [Your app name]
e. Authorized JavaScript origins: Add your server's domain (e.g., http://localhost:3000 for local development)
Build a Professional Email Service: Gmail OAuth Express   Webhooks
f. Authorized redirect URIs:
- Add: https://developers.google.com/oauthplayground
- Add your server's callback URL if you have one (e.g., http://localhost:3000/auth/google/callback)
g. Click "Create"
h. A popup will show your Client ID and Client Secret. Save these securely.


Step-5: Get a new Refresh Token:
a. Go to https://developers.google.com/oauthplayground/

Build a Professional Email Service: Gmail OAuth Express   Webhooks

b. Click the gear icon(Like Settings) in the top right corner
c. Click on check box "Use your own OAuth credentials"
d. Enter your new Client ID and Client Secret
e. Close the settings
f. In the left sidebar, find "Gmail API v1"
g. Select https://mail.google.com/
h. Click "Authorize APIs"
i. Choose your Google account and grant the requested permissions
j. On the next screen, click "Exchange authorization code for tokens"
k. Copy the "Refresh token" from the response

If you encounter any issues during this process or when testing the email functionality, please provide the specific error messages or behavior you're seeing in comments.


The Code Explained

Let's break down the implementation step by step:

1. Initial Setup and Dependencies

npm install express body-parser nodemailer googleapis dotenv
Copy after login
Copy after login
Copy after login

This section sets up our Express server and imports necessary dependencies. We use body-parser to parse JSON requests and dotenv to manage environment variables.

2. OAuth2 Configuration

CLIENT_ID=your_client_id
CLIENT_SECRET=your_client_secret
REDIRECT_URI=your_redirect_uri
REFRESH_TOKEN=your_refresh_token
EMAIL_USER=your_email@gmail.com
Copy after login
Copy after login

We create an OAuth2 client using Google's authentication library. This handles token refresh and authentication with Gmail's API.

3. Email Sending Function

const express = require("express");
const bodyParser = require("body-parser");
const nodemailer = require("nodemailer");
const { google } = require("googleapis");
require("dotenv").config();

const app = express();
app.use(bodyParser.json());
Copy after login

This function:

  • Extracts data from the webhook payload, you can modify payload based on needs
  • Gets a fresh access token
  • Creates a transport with OAuth2 authentication
  • Sends the email with customized content

4. Webhook Endpoint

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

Our webhook endpoint:

  • Receives POST requests
  • Processes the webhook data
  • Sends emails
  • Returns appropriate responses

Testing

Test your webhook using curl or Postman:

npm install express body-parser nodemailer googleapis dotenv
Copy after login
Copy after login
Copy after login

Troubleshooting

Common issues and solutions:

  1. Authentication Errors: Check your OAuth2 credentials
  2. Token Expiration: Ensure refresh token is valid
  3. Missing Data: Validate webhook payload

Conclusion

You now have a secure, OAuth2-authenticated email notification system! This implementation provides a solid foundation for building more complex notification systems while maintaining security and reliability.

Hope this post is useful for you to setting up email service.

Happy coding! ?

The above is the detailed content of Build a Professional Email Service: Gmail OAuth Express Webhooks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1242
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles