Cloud Storage & File Managementintermediate
October 26, 2025
7 min read
45 minutes
Build an AI Email Filter That Actually Understands Your Inbox
Automate your Gmail cleanup with n8n and Google Gemini AI. Delete spam, marketing, and unwanted emails intelligently—no manual filtering needed.
By Mahedi Hasan Nadvee

Your inbox is drowning in marketing emails, promotional offers, and system alerts you never asked for. You spend precious minutes every day clicking delete, unsubscribe, and marking as spam. Traditional email filters miss the nuance between a billing notification you need and a promotional email disguised as important news.
What if your email could clean itself? Not with rigid rules that break when senders change their subject lines, but with actual intelligence that understands context like you do.
This n8n workflow uses Google Gemini AI to read your emails the way a human assistant would. It evaluates each message, assigns confidence scores for unwanted content, marketing, and spam, then automatically deletes what you don't need while keeping what matters. The best part? It learns the difference between a security alert worth keeping and a device notification you can ignore.
What You Need to Get Started
Before building this intelligent email automation, you'll need access to a few key services:
- Gmail Account: The workflow connects directly to Gmail to fetch and manage your emails
- Google Gemini API: Powers the AI analysis that classifies each email with human-like understanding
- Telegram Bot: Sends you real-time notifications about deleted emails and system errors
- n8n Instance: The workflow automation platform where you'll build and run this system
Key Components of the Workflow
This automation relies on several specialized n8n nodes working together:
- Gmail Nodes: Retrieve emails, delete unwanted messages, and manage labels
- AI Agent with Google Gemini: The brain of the operation that reads and classifies emails
- Structured Output Parser: Ensures the AI returns consistent, actionable data
- Conditional Logic Node: Routes emails to deletion or preservation based on AI scores
- Telegram Nodes: Keep you informed about every action taken
- Loop Control Nodes: Process emails in manageable batches across date ranges
Building Your AI Email Manager Step by Step
Step 1: Set Up the Processing Loop
The workflow starts with a manual trigger and immediately initializes loop variables. This clever design processes your emails in batches, looking back 14 days but handling them in 3-day chunks. Why batches? Gmail API limits and AI processing costs make it smarter to work incrementally.
The loop variable tracks which page you're on, letting the workflow pick up where it left off. Each iteration increments the page counter, calculates the date range dynamically, and feeds that to Gmail. This means you can process thousands of emails without overwhelming your system or hitting rate limits.
Step 2: Fetch Emails with Smart Filtering
The Gmail node pulls messages using a carefully crafted query. It excludes emails already labeled as processed (using the n8n-skipped label) and focuses on the calculated date range. This prevents duplicate processing and ensures you're only analyzing emails once.
The returnAll parameter set to true means every matching email gets pulled into the workflow. These raw email objects contain everything: sender, subject, body, timestamps, and more. All of this data flows into the AI agent for analysis.
Step 3: Let AI Classify Each Email
Here's where the magic happens. The AI Agent node receives each email and sends it to Google Gemini with specific instructions. The prompt tells the AI to act like your personal email assistant, classifying messages with three decimal scores between 0 and 1.
The AI evaluates:
- isUnwantedConfidence: How certain is it this email serves no purpose?
- isMarketingConfidence: Is this promotional content or sales outreach?
- isSpamConfidence: Does this look like spam or phishing?
image_1.png
But the instructions go deeper. The AI knows to treat billing statements, invoices, job applications, and security alerts as wanted content (scoring near 0). Meanwhile, promotional emails, setup reminders, and irrelevant system alerts get flagged as unwanted (scoring toward 1). Device activity notifications like "sound played" or "location pinged" are marked unwanted unless they're genuinely security-related.
The Structured Output Parser ensures the AI returns data in a predictable format with the email ID, all three confidence scores, a brief explanation, and the sender's address. This consistency makes the next steps reliable.
Step 4: Make the Delete or Keep Decision
The If node examines the AI's verdict. If any of the three confidence scores exceeds 0.5, the email takes the deletion path. This OR logic means an email only needs to be confidently unwanted, marketing, or spam in one category to get removed.
Emails that don't meet the threshold go down the false branch, where they're simply re-labeled back into your inbox. This conservative approach means when the AI is uncertain, it errs on the side of keeping the email. You'd rather manually delete one promotional email than lose an important message.
Step 5: Take Action and Notify
For emails marked for deletion, the workflow calls the Gmail delete operation using the email ID. Success triggers a Telegram message with the sender and the AI's reasoning. This real-time notification lets you audit the system's decisions without opening Gmail.
For preserved emails, a different Telegram message says "Skipping Email" with the same context. If the deletion fails or the AI encounters an error, separate Telegram nodes alert you immediately. This comprehensive notification system means you're never in the dark about what's happening to your inbox.
image_2.png
Every outcome (deleted, skipped, AI error, deletion failure) flows into a Success node, then gets aggregated. The workflow then increments the page counter and loops back to process the next batch of emails. This continues until all emails in the 14-day window are processed.
Step 6: Handle Errors Gracefully
Throughout the workflow, error handling ensures nothing breaks silently. The AI Agent node has retry logic if Gemini times out. Both Gmail delete and Telegram notification nodes have error outputs that trigger alternative notification paths.
If the AI can't classify an email, you get notified with the full error details. If Gmail refuses to delete a message (maybe it's already gone), you know immediately. This defensive design keeps the automation running smoothly even when individual operations fail.
Why This Workflow Changes Everything
Traditional email filters rely on keywords, sender blacklists, and simple pattern matching. They break when marketing teams get creative with subject lines or when legitimate services send promotional content. This AI-powered approach understands context.
The workflow handles edge cases beautifully. A security alert from your bank stays in your inbox. A promotional email from that same bank offering credit card deals gets deleted. The AI distinguishes between them by reading the actual content and intent, not just the sender.
You save hours every week not manually triaging emails. Your inbox stays clean without you lifting a finger. The Telegram notifications give you confidence the system is working and let you spot-check its decisions. Over time, you'll notice patterns in what gets removed and can adjust the confidence threshold if needed.
Real-World Use Cases
Busy professionals use this to maintain inbox zero effortlessly. Freelancers keep client communications pristine while filtering out endless service provider updates. Small business owners let AI handle the flood of marketing emails so they can focus on actual customer messages.
The workflow runs on a schedule (though currently set to manual trigger in this version). Set it to run daily or weekly depending on your email volume. The batch processing approach means it handles 100 emails or 10,000 with the same reliability.
You can customize the AI prompt to match your preferences. Want to be more aggressive with deletions? Lower the threshold to 0.3. Need to preserve certain types of newsletters? Add that to the AI instructions. The structured output format makes these adjustments straightforward.
Take Control of Your Inbox Today
Email overload isn't a discipline problem. It's an automation problem. You shouldn't spend mental energy deciding if each message deserves space in your inbox. That's exactly what AI excels at: making consistent, context-aware decisions at scale.
This n8n workflow gives you a personal email assistant that never sleeps, never gets overwhelmed, and improves the quality of your digital life one deleted promotional email at a time. Your inbox will thank you, and so will your productivity.
Share this article
Help others discover this content
Tap and hold the link button above to access your device's native sharing options
More in Cloud Storage & File Management
Continue exploring workflows in this category
