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:
find_emails(query, limit)delete_email(message_id)get_email_details(message_id)
Goal: Build reusable email utility class.
Challenge 2: Specialized Finders
Add methods to find:
- Emails older than N days
- Emails with attachments > N MB
- Emails from specific sender
Goal: Build specialized queries.
Challenge 3: Statistics & Reporting
Extend class with:
- Track deleted/archived count
- Calculate storage freed
- Generate cleanup report
Goal: Build comprehensive reporting.