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