Building Email Utilities

Gmail Cleanup — Building Email Utilities
Gmail Cleanup — Practical Scripting
Course 1 · Chapter 4 · Building Email Utilities

🔧 Building Email Utilities

Now that you understand the Gmail API, it's time to build reusable utility functions. This chapter teaches modular design: creating helper functions that you can use in different ways, handle errors gracefully, and test independently.

📦 Utility Module Design

class GmailCleanup: """Reusable Gmail cleanup utilities.""" def __init__(self, service, config): self.service = service self.config = config self.deleted_count = 0 self.archived_count = 0 self.total_storage_freed = 0 def find_emails(self, query: str, limit: int = 10) -> list: """Find emails matching query.""" try: results = self.service.users().messages().list( userId='me', q=query, maxResults=limit ).execute() return results.get('messages', []) except Exception as e: print(f"❌ Error finding emails: {e}") return [] def delete_email(self, message_id: str) -> bool: """Delete a single email.""" try: self.service.users().messages().delete( userId='me', id=message_id ).execute() self.deleted_count += 1 return True except Exception as e: print(f"❌ Error deleting email: {e}") return False def archive_email(self, message_id: str) -> bool: """Archive email (remove from inbox label).""" try: self.service.users().messages().modify( userId='me', id=message_id, body={'removeLabelIds': ['INBOX']} ).execute() self.archived_count += 1 return True except Exception as e: print(f"❌ Error archiving email: {e}") return False def get_stats(self) -> dict: """Get cleanup statistics.""" return { 'deleted': self.deleted_count, 'archived': self.archived_count, 'storage_freed_mb': self.total_storage_freed }

🎯 Key Utility Functions

Find Old Emails

def find_old_emails(self, days: int) -> list: from datetime import datetime, timedelta cutoff = (datetime.now() - timedelta(days=days)).strftime('%Y/%m/%d') query = f"before:{cutoff}" return self.find_emails(query)

Find Large Attachments

def find_large_attachments(self, min_size_mb: int) -> list: min_bytes = min_size_mb * 1024 * 1024 query = f"has:attachment size:{min_bytes}" return self.find_emails(query)

Find from Sender

def find_from_sender(self, sender: str) -> list: query = f"from:{sender}" return self.find_emails(query)

💻 Coding Challenges

Challenge 1: Build GmailCleanup Class

Create GmailCleanup class with methods:

  1. find_emails(query, limit)
  2. delete_email(message_id)
  3. get_email_details(message_id)

Goal: Build reusable email utility class.

→ Solution

Challenge 2: Specialized Finders

Add methods to find:

  1. Emails older than N days
  2. Emails with attachments > N MB
  3. Emails from specific sender

Goal: Build specialized queries.

→ Solution

Challenge 3: Statistics & Reporting

Extend class with:

  1. Track deleted/archived count
  2. Calculate storage freed
  3. Generate cleanup report

Goal: Build comprehensive reporting.

→ Solution