Complete Cleanup Workflow
Gmail Cleanup — Practical Scripting
Course 1 · Chapter 5 · Complete Cleanup Workflow
🔄 Complete Cleanup Workflow
Now it's time to bring everything together: configuration, API connection, utility functions, and safety checks. This chapter teaches you how to orchestrate a complete, safe cleanup workflow that finds emails, previews them, and deletes or archives them with full reporting.
📋 The Cleanup Workflow
Step 1: Load Configuration
Read .env file and validate settings
Step 2: Authenticate
Connect to Gmail API using OAuth
Step 3: Find Emails
Query for emails matching cleanup criteria
Step 4: Preview Results
Display what will be deleted (safety check!)
Step 5: Confirm Action
Ask user before deleting (never automatic!)
Step 6: Execute Cleanup
Delete or archive emails
Step 7: Report Results
Show what was deleted and storage freed
🔧 Main Cleanup Script
import sys
from config import Config
from gmail_utils import get_gmail_service, GmailCleanup
def preview_emails(emails: list, cleanup: GmailCleanup, limit: int = 5):
"""Show sample of emails to be deleted."""
print("\n📋 PREVIEW (first 5):")
print("-" * 80)
for email in emails[:limit]:
details = cleanup.get_email_details(email['id'])
if details:
print(f"Subject: {details['subject']}")
print(f"From: {details['from']}")
print(f"Date: {details['date']}")
print(f"Size: {details['size_mb']:.2f} MB")
print("-" * 80)
def confirm_action(email_count: int) -> bool:
"""Ask user to confirm deletion."""
print(f"\n⚠️ About to delete {email_count} emails!")
response = input("Type 'yes' to confirm: ")
return response.lower() == 'yes'
def main():
"""Main cleanup workflow."""
print("=" * 80)
print("🚀 Gmail Cleanup Utility")
print("=" * 80)
# Step 1: Load configuration
print("\n📋 Loading configuration...")
config = Config()
if not config.validate():
return False
# Step 2: Connect to Gmail
print("🔌 Connecting to Gmail...")
service = get_gmail_service()
cleanup = GmailCleanup(service, config)
# Step 3: Find old emails
print(f"\n🔍 Finding emails older than {config.days_old} days...")
emails = cleanup.find_old_emails(config.days_old)
if not emails:
print("✅ No old emails found!")
return True
print(f"✅ Found {len(emails)} emails")
# Step 4: Preview results
preview_emails(emails, cleanup)
# Step 5: Confirm action
if not confirm_action(len(emails)):
print("❌ Cleanup cancelled")
return False
# Step 6: Execute cleanup
print("\n🗑️ Deleting emails...")
for email in emails:
cleanup.delete_email(email['id'])
# Step 7: Report results
stats = cleanup.get_stats()
print("\n" + "=" * 80)
print("✅ CLEANUP COMPLETE!")
print("=" * 80)
print(f"Emails deleted: {stats['deleted']}")
print(f"Storage freed: {stats['storage_freed_mb']:.2f} MB")
return True
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)
⚠️ Safety Features
- ✅ Configuration validation (catches errors early)
- ✅ Preview of emails before deletion (visual confirmation)
- ✅ User confirmation prompt (prevents accidents)
- ✅ Error handling throughout (graceful failures)
- ✅ Comprehensive reporting (what happened)
💻 Coding Challenges
Challenge 1: Safe Deletion
Create a workflow that:
- Finds 10 old emails
- Displays subject, sender, date for preview
- Asks user to confirm (input validation)
- Deletes only if confirmed
Goal: Build safe, user-friendly deletion.
Challenge 2: Multi-Criteria Cleanup
Build cleanup that finds and deletes:
- Emails older than 365 days
- Emails with large attachments
- Emails from specific senders
Goal: Handle multiple cleanup criteria.
Challenge 3: Complete Workflow
Build the full cleanup script with:
- Configuration loading and validation
- Gmail authentication
- Finding and previewing emails
- User confirmation
- Deletion and reporting
Goal: End-to-end cleanup automation.