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:

  1. Finds 10 old emails
  2. Displays subject, sender, date for preview
  3. Asks user to confirm (input validation)
  4. Deletes only if confirmed

Goal: Build safe, user-friendly deletion.

โ†’ Solution

Challenge 2: Multi-Criteria Cleanup

Build cleanup that finds and deletes:

  1. Emails older than 365 days
  2. Emails with large attachments
  3. Emails from specific senders

Goal: Handle multiple cleanup criteria.

โ†’ Solution

Challenge 3: Complete Workflow

Build the full cleanup script with:

  1. Configuration loading and validation
  2. Gmail authentication
  3. Finding and previewing emails
  4. User confirmation
  5. Deletion and reporting

Goal: End-to-end cleanup automation.

โ†’ Solution