AI-Powered Gmail Email Classifier & Labeler
Overview
This workflow automatically monitors your Gmail inbox for new emails, retrieves the full email content, and uses an AI agent powered by Anthropic's Claude to classify each email into a predefined Gmail label. It also checks prior email history with the sender to improve classification accuracy. Finally, it applies the chosen label to the email, helping you organize your inbox without manual effort.
How It Works
- Gmail Trigger — Polls Gmail every minute for new emails (OAuth2).
- Gmail — Fetches the full email details (headers, body, etc.) using the message ID from the trigger (OAuth2).
- AI Agent — Orchestrates the classification process. It uses the Anthropic Chat Model as its language model and the Structured Output Parser to extract the label ID. The agent also has access to two Gmail tools to check prior email history.
- Anthropic Chat Model — The LLM (Claude Sonnet 4) that analyzes the email content and history to decide the best label (API Key auth).
- Structured Output Parser — Ensures the AI's response is a valid JSON object containing the label ID (No auth).
- Get Email — A Gmail tool used by the AI agent to search for prior emails from the sender (OAuth2).
- Check Sent — A Gmail tool used by the AI agent to check if the user has previously sent emails to the sender (OAuth2).
- Gmail1 — Applies the chosen label to the original email (OAuth2).
Node Details
- Gmail Trigger (OAuth2) — Polls Gmail every minute for new messages. No filters are set, so it watches the entire inbox.
- Gmail (OAuth2) — Uses the
getoperation to retrieve the full email object bymessageId. Thesimpleoption is disabled to get the raw JSON. - Anthropic Chat Model (API Key auth) — Configured to use the
claude-sonnet-4-20250514model with default options. - AI Agent (No auth) — Contains a detailed system message that instructs the AI to classify emails into one of six labels (To Respond, FYI, Comment, Notification, Meeting Update, Marketing) based on content, headers, and prior email history. It uses the
textinput "Run the task." and has an output parser attached. - Structured Output Parser (No auth) — Expects a JSON schema with keys
labelandlabel ID. This forces the AI to output a clean JSON object. - Get Email (OAuth2) — Gmail tool that searches for emails from the sender using the
from:query. It returns all matching emails (no limit). - Check Sent (OAuth2) — Gmail tool that searches for emails sent to the sender in the
SENTfolder, using theto:query. - Gmail1 (OAuth2) — Uses the
addLabelsoperation to apply the label ID returned by the AI agent to the original email.
Setup Instructions
- Gmail OAuth2 Credentials — You need a Google Cloud project with the Gmail API enabled. Create OAuth2 credentials (Desktop app or Web application) and add them in n8n under Credentials > Google. The workflow uses OAuth2 for all Gmail nodes.
- Anthropic API Key — Sign up at Anthropic and generate an API key. Add it in n8n under Credentials > Anthropic.
- Gmail Labels — The workflow expects specific label IDs (e.g.,
Label_5151750749488724401for "To Respond"). You must create these labels in your Gmail account and note their IDs. Alternatively, you can modify the system message in the AI Agent node to use your own label names/IDs. - Activate the workflow — Once credentials are set and labels exist, activate the workflow. It will start polling Gmail and classifying new emails.
Use Cases & Variations
- Personal Inbox Zero — Automatically sort newsletters, notifications, and actionable emails into separate folders.
- Sales Pipeline Management — Classify incoming leads as "To Respond" or "Marketing" based on prior contact.
- Support Ticket Triage — Route customer emails to appropriate labels based on content and history.
- Custom Labels — Modify the AI agent's system prompt to use your own set of labels (e.g., "Urgent", "Read Later", "Archive").
- Integration with Other Tools — After labeling, you could add nodes to send Slack notifications, create tasks in Notion, or log to a spreadsheet.
Workflow JSON
{
"id": "uf6t5qhnQMgilteE",
"meta": {
"instanceId": "[REDACTED_INSTANCE_ID]",
"templateCredsSetupCompleted": true
},
"name": "Email Manager",
"tags": [
{
"id": "[REDACTED_TAG_ID]",
"name": "Personal Assistant",
"createdAt": "2025-05-28T13:58:43.876Z",
"updatedAt": "2025-05-28T13:58:43.876Z"
}
],
"nodes": [
{
"id": "5e01a927-caf7-41ad-aca7-d7504e313564",
"name": "Gmail Trigger",
"type": "n8n-nodes-base.gmailTrigger",
"position": [
-20,
-60
],
"parameters": {
"filters": {},
"pollTimes": {
"item": [
{
"mode": "everyMinute"
}
]
}
},
"credentials": {
"gmailOAuth2": {
"id": "credential-id",
"name": "gmailOAuth2 Credential"
}
},
"typeVersion": 1.2
},
{
"id": "a8644856-a8bf-49de-84a7-3fd9f93550d3",
"name": "Gmail",
"type": "n8n-nodes-base.gmail",
"position": [
200,
-20
],
// ... truncated (copy to see full JSON)How to Import This Workflow
- 1Copy the workflow JSON above using the Copy Workflow JSON button.
- 2Open your n8n instance and go to Workflows.
- 3Click Import from JSON and paste the copied workflow.
Don't have an n8n instance? Start your free trial at n8nautomation.cloud
Related Templates
Telegram Bot TikTok Video Downloader (No Watermark)
Overview This workflow transforms your Telegram bot into a powerful TikTok video downloader without watermarks. When a user sends a TikTok link to the bot, it automatically validates the URL, fetches the video page, extracts the clean video URL, downloads the file, and sends it back to the user with statistics (views, likes, author). The entire process is handled seamlessly with real-time status updates and robust error handling. This is perfect for content curators, social media managers, or anyone who wants to save TikTok videos without watermarks directly from Telegram. The bot provides a smooth user experience with progress messages and clear error feedback. Workflow Steps Telegram Trigger (No auth) — Listens for incoming messages from Telegram users. Configured to receive only updates. This node requires a Telegram Bot Token set up in n8n credentials. Validate TikTok URL (No auth) — An IF node that checks if the received message contains in the text. Uses string contains operator with loose type validation. Routes valid URLs to the processing path and invalid ones to an error message. Send Invalid URL Message (Telegram API Key auth) — Sends a friendly error message to the user explaining they need to provide a valid TikTok link with examples. Uses the chat ID from the original trigger message. Send Chat Action (Telegram API Key auth) — Sends a "uploading video" chat action to show the user that the bot is processing their request. This provides visual feedback in the Telegram chat. Send Processing Message (Telegram API Key auth) — Sends a status message "⏳ Downloading video... Please wait!" to keep the user informed about the progress. Configure Variables (No auth) — A Set node that stores the video URL (trimmed) and chat ID as named variables for use in subsequent nodes. This ensures data persistence through the workflow. Get TikTok Page HTML (No auth) — An HTTP Request node that fetches the TikTok video page HTML. Uses browser-like headers (User-Agent, Accept, Accept-Language) to mimic a real browser request. Configured with a 30-second timeout and full response capture. On error, it continues to the error handling path. Extract Video URL (No auth) — A Code node running JavaScript that parses the HTML to find the script tag containing video metadata. Extracts the video URL (playAddr or downloadAddr), cookies, description, author, and statistics (plays, likes, comments). On error, it routes to the error handler. Download Video File (No auth) — An HTTP Request node that downloads the actual video file using the extracted URL. Includes cookies from the previous step, proper referrer header, and a 60-second timeout. Configured to return binary file data. On error, it routes to the error handler. Delete Process Notif (Telegram API Key auth) — Deletes the "Processing..." status message to clean up the chat after the video is ready. Uses the message ID from the earlier status message. Send Video to User (Telegram API Key auth) — Sends the downloaded video file to the user with a formatted caption showing the author, view count, and like count. Uses binary data mode for file upload. Format Error (No auth) — A Code node that captures error messages from failed nodes and formats them into a user-friendly error object with the chat ID for response. Send Error Message (Telegram API Key auth) — Sends a detailed error message to the user explaining possible reasons for failure (deleted video, invalid link, maintenance, restrictions) with HTML formatting. Setup Instructions Prerequisites Telegram Bot Token: Create a bot via @BotFather on Telegram and get your API token n8n Instance: Self-hosted or cloud n8n (n8n.io) Configuration Steps Telegram Credentials: In n8n, go to Credentials → New → Telegram API. Enter your bot token from BotFather Webhook Setup: The Telegram Trigger node automatically sets up a webhook URL. Make sure your n8n instance is publicly accessible or use a tunnel (ngrok) Test the Bot: Send any TikTok video link to your bot (e.g., ) Use Cases & Variations Primary Use Case Personal Video Archiving: Save your favorite TikTok videos without watermarks for offline viewing Content Curation: Collect videos for repurposing on other platforms Social Media Management: Download client videos for scheduling tools Possible Adaptations Add Multiple Platforms: Extend the workflow to support Instagram Reels, YouTube Shorts, or Twitter videos by adding additional validation and extraction logic Database Storage: Add a Google Sheets or Airtable node to log downloaded videos with metadata Admin Notifications: Add a second Telegram channel to notify you when someone downloads a video Rate Limiting: Implement user rate limiting using n8n's Wait node or a database Video Processing: Add FFmpeg or other processing nodes to convert formats or add watermarks Multi-language Support: Modify error messages and captions based on user language preferences
YouTube Video Summarizer with Telegram Notification
High-Level Summary This workflow automatically processes YouTube videos by fetching their transcripts, generating a structured AI-powered summary using OpenAI's GPT-4o-mini, and sending the summary along with video metadata to a Telegram chat. It is triggered via a webhook, making it easy to integrate with other tools or services (e.g., a browser extension, a form, or another automation). The workflow is ideal for content curators, researchers, or teams who want to quickly digest video content without watching the full video. Workflow Steps Webhook — Receives an incoming HTTP POST request containing a YouTube URL in the request body. This is the entry point of the workflow. (No auth) Get YouTube URL (Set node) — Extracts the field from the incoming webhook payload and stores it as a string variable for downstream use. (No auth) YouTube Video ID (Code node) — Runs a JavaScript function that parses the YouTube URL using a regex pattern to extract the 11-character video ID (supports both and formats). (No auth) Get YouTube Video (YouTube node) — Uses the extracted video ID to fetch video metadata (title, description, etc.) from the YouTube Data API v3. (OAuth2 — requires a Google Cloud project with YouTube Data API enabled) YouTube Transcript (Community node: ) — Fetches the transcript/captions for the video. This node requires the video ID (passed from the previous step). (No auth — uses public YouTube captions) Split Out (SplitOut node) — Splits the transcript array into individual items so each text segment can be processed separately. (No auth) Concatenate (Summarize node) — Concatenates all transcript text segments into a single string, separated by spaces, to prepare the full transcript for analysis. (No auth) gpt-4o-mini (OpenAI Chat Model node) — Configures the OpenAI language model (GPT-4o-mini) that will be used for summarization. (API Key auth — requires an OpenAI API key) Summarize & Analyze Transcript (LLM Chain node) — Sends the concatenated transcript to the GPT-4o-mini model with a detailed prompt asking for a structured summary with headers, bullet points, bold terms, and tables. The output is a markdown-formatted analysis. (No auth — uses the model configured in the previous node) Response Object (Set node) — Assembles the final output object containing: - : The AI-generated summary text - : An empty array (placeholder for future use) - : The video title from YouTube metadata - : The video description from YouTube metadata - : The YouTube video ID - : The original YouTube URL from the webhook (No auth) Respond to Webhook — Sends the assembled response object back to the original webhook caller (e.g., a browser extension or app). (No auth) Telegram — Sends a message to a specified Telegram chat containing the video title and the YouTube URL. (API Key auth — requires a Telegram Bot Token and chat ID) Setup Instructions To use this workflow, you will need the following accounts and credentials: OpenAI Account: Create an account at platform.openai.com and generate an API key. Add this as a credential in n8n under "OpenAI". Google Cloud Project: Enable the YouTube Data API v3 in your Google Cloud Console, create OAuth 2.0 credentials (Desktop app type), and add them in n8n under "YouTube OAuth2 API". Telegram Bot: Create a bot via @BotFather on Telegram to get a Bot Token. Find your chat ID (e.g., by messaging your bot and visiting ). Add the token as a credential in n8n under "Telegram API". Webhook URL: After activating the workflow, copy the production webhook URL (e.g., ). You will send POST requests to this URL with a JSON body like . Use Cases and Variations Content Curation: Automatically summarize long conference talks, tutorials, or webinars and share them with your team on Telegram. Research Assistant: Collect video transcripts and AI summaries for later reference or database storage. Browser Extension Integration: Pair this workflow with a browser extension that sends the current YouTube URL to the webhook when clicked. Variations: - Replace Telegram with Slack, Discord, or email notifications. - Store summaries in a Google Sheet or Airtable for a searchable archive. - Add a filter to skip videos shorter than a certain duration. - Use a different LLM (e.g., Claude, Gemini) by swapping the OpenAI node. - Add error handling to notify you if a video has no captions.
Spotify Monthly Playlist Builder from Liked Songs
Overview This workflow automatically creates a monthly Spotify playlist containing all the songs you've liked during that month. It runs on a schedule (e.g., daily) and ensures that every new liked track is added to a dedicated monthly playlist. It also maintains a NocoDB database as a persistent record of your playlists and tracks, preventing duplicates and enabling historical tracking. This is perfect for users who want to automatically archive their liked songs by month, creating a personal music diary without any manual effort. The workflow handles playlist creation, track deduplication, and database synchronization entirely on its own. Workflow Steps Schedule Trigger (No auth) — Runs the workflow on a configurable interval (currently set to every minute for testing; adjust to daily or weekly for production). Get current date (No auth) — A Code node that calculates the current month and year, formatting it as a text string like "September '25". This is used as the playlist name and database key. Get all user playlist (OAuth2) — Fetches all playlists from the authenticated Spotify user's account using Spotify's API. Get monthly playlist (No auth) — A Filter node that checks if a playlist with the current month's name already exists among the user's Spotify playlists. Monthly playlist exist in Spotify? (No auth) — An IF node that branches based on whether the monthly playlist was found in Spotify. - If Yes (playlist exists): Proceeds to check the database. - If No (playlist does not exist): Goes to create a new playlist. Create playlist in Spotify (OAuth2) — Creates a new Spotify playlist with the current month's name and a description "Monthly playlist". Create playlist in DB1 (API Key auth) — Inserts the newly created Spotify playlist's URI, name, and description into the NocoDB table. Get playlist in DB (API Key auth) — Queries the NocoDB table to see if the current month's playlist is already recorded. Playlist exist in DB? (No auth) — An IF node that checks if the playlist record exists in the database. - If Yes: Proceeds to the merge step. - If No: Creates a database record for the existing Spotify playlist. Create playlist in DB (API Key auth) — Inserts the existing Spotify playlist's details into NocoDB. Merge (No auth) — A Merge node that combines the two branches (playlist already existed vs. newly created) into a single output. Get this month playlist in DB (API Key auth) — Retrieves the current month's playlist record from NocoDB to get its URI. Get this month tracks in DB (API Key auth) — Fetches all tracks that have been saved in NocoDB for the current month's playlist. For each monthly tracks in DB (No auth) — A SplitInBatches node that iterates over each track record from the database. Get this month tracks in Spotify (OAuth2) — Fetches all tracks currently in the Spotify monthly playlist. Filter1 (No auth) — A Filter node that checks if the current database track's URI matches any track already in the Spotify playlist. Song is not present in the playlist? (No auth) — An IF node that triggers if the track is NOT found in the Spotify playlist. - If Not Present: Adds the track to the Spotify playlist. - If Present: Does nothing (cleanup node). Add song to the playlist (OAuth2) — Adds the track to the Spotify monthly playlist using its URI. Get last 10 liked tracks (OAuth2) — Fetches the user's 10 most recently liked tracks from Spotify. For each tracks in liked song (No auth) — A SplitInBatches node that iterates over each liked track. Check if track is saved (API Key auth) — Queries NocoDB to see if the track's URI already exists in the table. Is not saved (No auth) — An IF node that triggers if the track is NOT yet in the database. - If Not Saved: Creates a new database entry for the track. - If Saved: Does nothing. Create song entry (API Key auth) — Inserts the track's URI, added_at date, and playlist name into the NocoDB table. End (No auth) — A NoOp node that marks the end of the workflow. Setup Instructions Prerequisites A Spotify account (free or premium). A NocoDB instance (self-hosted or cloud) with two tables: and . Step 1: Configure NocoDB Create a new project in NocoDB. Create a table named with columns: (text), (text), (text). Create a table named with columns: (text), (text), (text). Note your Project ID and API Token from NocoDB settings. Step 2: Set up Spotify Credentials Go to the Spotify Developer Dashboard and create an app. Add as a redirect URI (or your n8n instance URL). In n8n, create a new Spotify OAuth2 credential with your Client ID and Client Secret. Step 3: Configure NocoDB Credentials In n8n, create a new NocoDB credential. Enter your NocoDB instance URL (e.g., ). Enter your API Token. Step 4: Update Node Parameters In all NocoDB nodes, replace the with your actual project ID. In the Schedule Trigger, adjust the interval to your preference (e.g., daily at 9 AM). The Get last 10 liked tracks node can be adjusted to fetch more tracks by changing the parameter. Use Cases & Variations Monthly Music Archive: Automatically create a new playlist each month with all your liked songs. Shared Family Playlist: Modify the workflow to add tracks to a shared family playlist instead of a personal one. Genre-Based Playlists: Use Spotify's audio features to categorize liked songs into genre-specific monthly playlists. Backup & Sync: Use this as a backup mechanism to ensure your liked songs are never lost, even if Spotify removes them. Multi-User Support: Adapt the workflow to run for multiple Spotify accounts by using different credentials. Customization Ideas Change the Schedule Trigger to run weekly or monthly instead of daily. Add a Telegram or Slack notification node to alert you when a new playlist is created. Use a Code node to filter tracks by artist or album before adding them to the playlist.