Opening Problem Statement
Meet Sarah, a busy project manager who struggles daily with an overflowing Gmail inbox filled with promotional emails, marketing alerts, and spam messages. Despite her best efforts to manually sort and delete these unwanted emails, it wastes her over an hour each day—time that could be better spent on critical tasks. The constant noise not only clutters her workspace but also causes her to miss important emails, creating stress and inefficiency.
Sarah’s specific challenge is filtering out unwanted emails automatically based on nuanced content signals, not just basic spam filters. She needs a smart, automated solution that understands the essence of each email, classifies it, and deletes or archives accordingly, with notifications about what actions were taken.
What This Automation Does
This unique n8n workflow leverages Gmail, Google Gemini AI, and Telegram along with several other nodes to automate Gmail inbox cleanup intelligently. When triggered, the workflow:
- Retrieves Gmail emails in 14-day batches using a paging system to avoid overloading the inbox scanning.
- Feeds each email’s full data into Google Gemini Chat Model AI to classify emails with confidence scores for unwanted, marketing, or spam categories.
- Uses a logical condition node to decide if an email surpasses a 0.5 confidence threshold for deletion.
- Deletes emails classified as unwanted, marketing, or spam from Gmail automatically.
- Sends real-time Telegram notifications summarizing each deletion, skipped email, or AI error for transparency and audit trails.
- Tracks and loops through pages until the complete inbox is scanned in chunks, ensuring comprehensive cleanup without manual intervention.
This method saves multiple hours weekly, proactively managing email clutter with precision and keeping inboxes lean and relevant.
Prerequisites ⚙️
- n8n account (Cloud or self-hosted). If you prefer self-hosting, consider options like Hostinger (https://buldrr.com/hostinger).
- Gmail account with OAuth2 credentials configured in n8n to allow API access.
- Google Gemini (PaLM) API access for AI classification.
- Telegram Bot account for sending notifications with chat ID and token configured.
Step-by-Step Guide to Build This Workflow
Step 1: Trigger the Workflow Manually
Navigate in n8n to Trigger → Manual Trigger node, name it When clicking ‘Test workflow’. This allows us to start the workflow for testing. You should see a “Execute Workflow” button after saving.
Step 2: Initialize Paging Variable for Email Batching
Create a Set node named Initialize Loop Vars. Add a variable page of type Number, set value to 0. This keeps track of which 14-day batch of emails we fetch.
Step 3: Increment Loop Variable for Paging
Add another Set node called Increment Loop Var. Add assignment for page defined with the following expression:
=({{ $('Forward Prev Page Num').isExecuted }) ? $('Forward Prev Page Num').first().json.prevPage + 1 : $('Initialize Loop Vars').first().json.pageThis code increases the page count after each batch completes.
Step 4: Fetch Emails From Gmail via Gmail Node
Add Gmail node called Gmail Get Email with operation “getAll”. Use filter query:
=before:{{ $now.minus(14 * $('Increment Loop Var').first().json.page, 'days').format('yyyy/MM/dd') }} after: {{ $now.minus(14 * ($('Increment Loop Var').first().json.page + 1), 'days').format('yyyy/MM/dd') }} -label:n8n-skipped
This fetches emails in 14-day intervals skipping those with label “n8n-skipped”.
Step 5: Use Google Gemini AI to Classify Emails
Add Google Gemini Chat Model node with model models/gemini-1.5-flash. Connect this to Gmail output. Parameters: AI will classify emails using this input prompt:
Classify the email with decimal values (0 to 1) for isUnwantedConfidence, isMarketingConfidence, and isSpamConfidence, where 0 means clearly wanted (e.g., billing, invoices, orders, job applications, security) and 1 means clearly unwanted (e.g., promotions, setup reminders, irrelevant alerts); treat system-generated alerts or device activity (like sound played, device found, location pinged) as unwanted unless security-related; use 0.5 as baseline and provide brief reasons.
Step 6: Parse AI Output for Structured Data
Add an Output Parser Structured node named Unwanted Email Output Parser. Apply a manual schema requiring emailId, isUnwantedConfidence, isMarketingConfidence, isSpamConfidence, briefReason, and emailFrom for proper data extraction from AI.
Step 7: Conditional Check for Unwanted or Spam Emails
Add an If node named If Unwanted Marketing or Spam with conditions checking if any of the three confidence scores exceed 0.5. This node decides if deletion will proceed.
Step 8: Delete Unwanted Emails from Gmail
Connect the true branch of the If node to another Gmail node named GmailDeleteEmail configured for the delete operation using the emailId from parsed output.
Step 9: Send Telegram Notification for Deleted Emails
Attach a Telegram node Telegram Sent Email Deleted Notification on successful email deletion reporting sender and reason.
Step 10: Send Telegram Notification for Skipped Emails
From the false branch of the If node, add Telegram node Telegram Sent Email Not Deleted Notification to report emails that were not deleted with relevant details.
Step 11: Error Handling Notification for AI Failures
Branch AI Check Email node’s error output to a Telegram node Telegram Sent AI Error Notification, alerting you if AI classification fails for any email.
Step 12: Aggregate Processing
Use an Aggregate node to combine all successful processed emails for tracking or further actions.
Step 13: Loop Paging
Use two Set nodes: Forward Prev Page Num updates previous page count with the current page number from Increment Loop Var node, then triggers Initialize Loop Vars to restart the whole paging loop until no more emails are fetched.
Step 14: Final Success No-Operation
Add No Operation node Success at ends of flows for clean workflow termination.
Customizations ✏️
- Adjust the
beforeandafterdate ranges inside the Gmail query to modify batch size from 14 days to your preferred interval, e.g., 7 or 30 days. - Modify confidence threshold values in the
If Unwanted Marketing or Spamnode to be more or less aggressive with deletions, such as 0.3 or 0.7. - Expand the AI prompt inside the
AI Check Emailnode to include custom categories or specialized keywords for your organizational context. - Change Telegram chat IDs or message formatting for different recipients or more detailed logs.
Troubleshooting 🔧
- Problem: “Can’t Delete Email” error appearing frequently.
Cause: Emails might be protected or already deleted, or bad emailId field mapping.
Solution: Verify that the Gmail node is mapped to the correctemailIdfrom the AI output parser and ensure the OAuth2 credentials have deletion permissions. - Problem: AI failure triggers Telegram error notifications.
Cause: Google Gemini API quota exceeded or prompt misformatted.
Solution: Check API limits, update prompt syntax, or add retry logic in the AI Check Email node settings. - Problem: Workflow loops endlessly without processing new emails.
Cause: Pagination variable not incrementing correctly.
Solution: Confirm correct logic inIncrement Loop VarandForward Prev Page Numnodes, and appropriate exit conditions.
Pre-Production Checklist ✅
- Verify Gmail OAuth2 credentials with full access including delete permissions.
- Test Telegram Bot sending messages to confirm chat ID and tokens are correct.
- Validate Google Gemini API key and confirm model access.
- Run the workflow manually and check logs for email classification and deletion results.
- Check AI output parser schema matches AI response structure.
Deployment Guide
Once tested, activate your workflow in n8n by switching from manual trigger to scheduled trigger or webhook. Monitor Telegram notifications for ongoing status and errors. Periodically review AI classification accuracy and adjust thresholds if needed to prevent false positives. Maintain API keys securely and renew credentials before expiration.
FAQs
- Can I use a different AI model instead of Google Gemini?
Yes, you can replace the Google Gemini Chat Model node with other AI nodes supported by n8n, like OpenAI GPT models, but you will need to adjust the prompt and output parsing accordingly. - Does deleting emails via Gmail API affect my email quota or limits?
Yes, frequent API calls for deletion count towards your quota; monitor usage to avoid hitting limits. - Is my email data safe during AI processing?
The workflow sends email content to Google Gemini API, so ensure your data privacy policies allow this or anonymize sensitive info before sending. - Can this workflow handle large inboxes with thousands of emails?
Yes, the paging mechanism with batching in 14-day intervals helps handle large volumes without timeout, but scale API quotas accordingly.
Conclusion
By completing this automation setup, you have built a smart Gmail cleanup system that leverages advanced AI classification with Google Gemini via n8n. This solution intelligently filters unwanted marketing and spam emails, reduces inbox clutter, and provides real-time notifications with Telegram.
You save hours weekly that used to be lost to manual email sorting, and maintain a sharper focus on important communications.
Next steps could include integrating additional labels for archiving, expanding AI categories for specialized filters, or linking to cloud storage for email backups.
Keep experimenting and refining your automation to match your evolving email needs!