================================================================================ GMAIL CLEANUP - CHALLENGE 2 SOLUTION Chapter 3: Gmail API Fundamentals Challenge: Query Emails ================================================================================ PROBLEM: Create functions to find: 1. Emails older than N days 2. Emails from specific sender 3. Emails with attachments larger than N MB SOLUTION: ================================================================================ File: gmail_utils.py (additions) from datetime import datetime, timedelta from gmail_utils import get_gmail_service def find_old_emails(service, days: int, limit: int = 10) -> list: """Find emails older than N days.""" cutoff_date = (datetime.now() - timedelta(days=days)).strftime('%Y/%m/%d') query = f"before:{cutoff_date}" try: results = service.users().messages().list( userId='me', q=query, maxResults=limit ).execute() messages = results.get('messages', []) print(f"✅ Found {len(messages)} emails older than {days} days") return messages except Exception as e: print(f"❌ Error: {e}") return [] def find_from_sender(service, sender: str, limit: int = 10) -> list: """Find emails from specific sender.""" query = f"from:{sender}" try: results = service.users().messages().list( userId='me', q=query, maxResults=limit ).execute() messages = results.get('messages', []) print(f"✅ Found {len(messages)} emails from {sender}") return messages except Exception as e: print(f"❌ Error: {e}") return [] def find_large_attachments(service, min_size_mb: int, limit: int = 10) -> list: """Find emails with attachments larger than N MB.""" min_bytes = min_size_mb * 1024 * 1024 query = f"has:attachment size:>{min_bytes}" try: results = service.users().messages().list( userId='me', q=query, maxResults=limit ).execute() messages = results.get('messages', []) print(f"✅ Found {len(messages)} emails with attachments > {min_size_mb}MB") return messages except Exception as e: print(f"❌ Error: {e}") return [] EXAMPLE USAGE ================================================================================ from gmail_utils import get_gmail_service, find_old_emails, find_from_sender, find_large_attachments service = get_gmail_service() # Find emails older than 1 year old_emails = find_old_emails(service, days=365) # Find emails from Gmail support support_emails = find_from_sender(service, sender="support@gmail.com") # Find emails with large attachments large_attachments = find_large_attachments(service, min_size_mb=10) GMAIL SEARCH SYNTAX ================================================================================ before:DATE Emails before date (2020/01/01) after:DATE Emails after date from:EMAIL Emails from sender to:EMAIL Emails to recipient has:attachment Emails with attachments filename:EXT Emails with file type size:>BYTES Emails larger than size subject:TEXT Emails with text in subject is:unread Unread emails is:starred Starred emails KEY PATTERNS ================================================================================ ✅ Query building (f-strings) ✅ API call with maxResults limit ✅ Error handling try/except ✅ Return empty list on error ✅ Friendly status messages ================================================================================