Gmail Automation
Build an automated email system with smart labeling, auto-responses, and AI-powered filtering
Live Example
Try out the code directly in your browser:
Let's build a Gmail automation system that:
- π Smart email classification by category (work, personal, social, promotion, spam, update)
- π¨ Urgency detection (high, medium, low) with prioritization
- π¬ Intelligent automated responses based on email context
- π·οΈ Automatic email organization (labeling, archiving)
- π Daily summary reports via Discord
- π Secure Gmail API integration with OAuth2 authentication flow
- β‘ Real-time email monitoring with webhook notifications
The Steps
Visual Overview
Here's how the automation flow works:

π Workflow Architecture
The Gmail Account Manager workflow consists of the following steps:
1. Gmail Authentication (Multi-Step Flow)
- Files:
steps/gmail-get-auth-url.step.ts
: Generates OAuth2 authorization URLsteps/gmail-auth.step.ts
: Handles authorization code exchangesteps/gmail-token-status.step.ts
: Checks token validity and refreshes if needed
2. Gmail Webhook (API Step)
- File:
steps/gmail-webhook.step.ts
- Purpose: Receives notifications from Gmail when new emails arrive
- Emits:
gmail.new_email
event with message details - Endpoint:
POST /api/gmail-webhook
3. Gmail Watch (API Step)
- File:
steps/gmail-watch.step.ts
- Purpose: Sets up push notifications for the Gmail account
- Endpoint:
GET /api/watch
4. Fetch Email (Event Step)
- File:
steps/fetch-email.step.ts
- Purpose: Retrieves the full email content from Gmail API
- Subscribes to:
gmail.email.received
- Emits:
gmail.email.fetched
with complete email data - Key Functions: Authenticates with Gmail API, fetches message content, parses attachments
5. Analyze Email (Event Step)
- File:
steps/analyze-email.step.py
- Purpose: Uses Hugging Face models to analyze email content
- Subscribes to:
gmail.email.fetched
- Emits:
gmail.email.analyzed
with analysis results - Analysis Performed:
- Category classification
- Urgency detection
- Sentiment analysis
- Key information extraction
6. Organize Email (Event Step)
- File:
steps/organize-email.step.ts
- Purpose: Applies labels and organization based on analysis
- Subscribes to:
gmail.email.analyzed
- Emits:
[gmail.email.organized, gmail.email.archived]
- Actions: Creates/applies labels, archives certain emails, marks importance
7. Auto-Respond to Email (Event Step)
- File:
steps/auto-responder.step.ts
- Purpose: Generates and sends appropriate responses for certain emails
- Subscribes to:
gmail.email.analyzed
- Emits:
gmail.email.responded
- Features:
- Template selection based on email context
- Personalization of responses
- Auto-reply for urgent messages
- Follow-up scheduling
8. Daily Summary (Cron Step)
- File:
steps/daily-summary.step.ts
- Purpose: Compiles and sends daily email activity summary
- Schedule: Runs daily at 6:00 PM
- Emits:
gmail.summary.sent
- Delivery: Sends report to Discord via webhook
Try It Out
π Prerequisites
- Node.js (v18+)
- Python (v3.8+)
- Gmail API credentials (client_id and client_secret)
- Google Cloud project with Pub/Sub API enabled
- Hugging Face API token
- Discord webhook URL (for daily summaries)
π Quick Start
-
Clone this repository
-
Install Node.js dependencies
-
Install Python dependencies
-
Configure environment variables
Then edit the
.env
file with your credentials (see setup sections below). -
Start the development server
-
Open the Motia Workbench
Navigate to http://localhost:3000 to access the workflow UI.
π§ Detailed Setup
Setting up Google Cloud Project and Gmail API
Before you can use the Gmail Account Manager, you need to set up a Google Cloud project with the Gmail API and Pub/Sub:
-
Create a Google Cloud Project:
- Go to Google Cloud Console
- Click on "New Project" and follow the steps to create a new project
- Note your project ID for later use
-
Enable the Gmail API:
- In your project, go to "APIs & Services" > "Library"
- Search for "Gmail API" and click on it
- Click "Enable"
-
Enable the Pub/Sub API:
- In your project, go to "APIs & Services" > "Library"
- Search for "Cloud Pub/Sub API" and click on it
- Click "Enable"
-
Create OAuth Credentials:
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Set the application type to "Desktop app"
- Click "Create"
- Note your Client ID and Client Secret for your
.env
file:
Setting up Google Pub/Sub for Gmail Notifications
To enable real-time email notifications, you need to set up a Google Cloud Pub/Sub topic and subscription:
-
Create a Pub/Sub Topic:
- In your Google Cloud Console, go to "Pub/Sub" > "Topics"
- Click "Create Topic"
- Name your topic (e.g.,
gmail-notifications
) - Add the service account
gmail-api-push@system.gserviceaccount.com
as a Topic Publisher to allow Gmail to publish notifications - Click "Create"
- Note the full topic name (usually
projects/your-project-id/topics/gmail-notifications
) for your.env
file:
-
Create a Pub/Sub Subscription:
- Once your topic is created, click "Create Subscription"
- Name your subscription (e.g.,
gmail-notifications-push
) - Set the Delivery Type to "Push"
- Set the Endpoint URL to your webhook URL (e.g.,
https://your-domain.com/api/gmail-webhook
)- For local development, you'll need to use a tool like ngrok to expose your local server
- Click "Create"
-
Set up Domain Verification (if needed):
- If you're using a custom domain for your webhook endpoint, you may need to verify domain ownership
- Follow the instructions in Google Cloud Console for domain verification
Gmail API Authentication
This project includes a complete OAuth2 authentication flow for the Gmail API:
- Start the development server:
pnpm dev
- Navigate to the authentication workflow in the Motia Workbench
- The workflow will generate an authorization URL
- Open the URL in your browser and authorize the application
- The application will receive and store your authentication tokens
Discord Webhook Configuration
To receive daily email summaries in Discord, follow these steps to set up a webhook:
-
Create a Discord Server (skip if you already have one):
- Open Discord and click the "+" icon on the left sidebar
- Select "Create My Own" and follow the setup wizard
-
Create a Channel for Notifications:
- Right-click on your server name and select "Server Settings"
- Go to "Channels" and click "Create Channel"
- Name it (e.g., "email-summaries") and click "Create"
-
Create a Webhook:
- Right-click on your new channel and select "Edit Channel"
- Go to "Integrations" tab
- Click "Create Webhook"
- Give it a name (e.g., "Gmail Summary Bot")
- Optionally, customize the avatar
- Click "Copy Webhook URL"
-
Add Webhook URL to Environment Variables:
- Open your
.env
file - Add or update the Discord webhook URL:
- Open your
-
Test the Webhook:
- You can test if your webhook is working correctly with this curl command:
- You should see the message appear in your Discord channel
- You can test if your webhook is working correctly with this curl command:
Hugging Face Setup
-
Create a Hugging Face Account:
- Sign up at Hugging Face
-
Generate an API Token:
- Go to your Hugging Face account settings
- Create a new API token
- Copy the token to your
.env
file:
π Project Structure
steps/
- Contains all workflow stepsgmail-get-auth-url.step.ts
- Generates OAuth2 URLgmail-auth.step.ts
- Handles OAuth2 flowgmail-token-status.step.ts
- Manages token refreshgmail-webhook.step.ts
- Webhook endpoint for Gmail notificationsgmail-watch.step.ts
- Sets up Gmail push notificationsfetch-email.step.ts
- Fetches email content from Gmail APIanalyze-email.step.py
- Python step for email analysis using Hugging Faceorganize-email.step.ts
- Organizes emails (labels, archives)auto-responder.step.ts
- Generates appropriate responsesdaily-summary.step.ts
- Sends daily summary to Discord
services/
- Shared service modulesconfig/
- Configuration files.motia/
- Motia framework configuration
π¦ Dependencies
Node.js Dependencies
- @motiadev/core, @motiadev/workbench, motia: Motia framework
- googleapis, google-auth-library: Google API integration
- gmail-api-parse-message-ts: Gmail message parsing
- axios: HTTP client
- zod: Schema validation
- react: UI components
Python Dependencies
- transformers, torch: Machine learning models
- scikit-learn, numpy, pandas: Data processing
- huggingface_hub: Access to Hugging Face models
- python-dotenv: Environment variable loading
π οΈ Troubleshooting
- Python Module Errors: Ensure you've installed all required Python packages with
pip install -r requirements.txt
- Authentication Errors: Verify your API credentials and follow the authentication flow
- Webhook Issues: Make sure the webhook endpoint is publicly accessible or properly configured for testing
- Token Refresh Errors: Check that your OAuth tokens are valid and that the refresh flow is working properly
- Pub/Sub Not Working: Verify that your Pub/Sub topic and subscription are properly configured and that your service account has the necessary permissions
π Environment Variables
Create a .env
file with the following variables: