================================================================================ GMAIL CLEANUP - CHALLENGE 3 SOLUTION Chapter 3: Gmail API Fundamentals Challenge: Parse and Report ================================================================================ PROBLEM: Create a script that: 1. Finds 10 old emails 2. Gets details for each (subject, sender, date, size) 3. Displays them in a table 4. Calculates total storage SOLUTION: ================================================================================ File: report_emails.py from gmail_utils import get_gmail_service, find_old_emails from config import Config def get_email_details(service, message_id: str) -> dict: """Get details about a single email.""" try: message = service.users().messages().get( userId='me', id=message_id ).execute() headers = message['payload']['headers'] subject = next((h['value'] for h in headers if h['name'] == 'Subject'), 'No Subject') sender = next((h['value'] for h in headers if h['name'] == 'From'), 'Unknown') date_str = next((h['value'] for h in headers if h['name'] == 'Date'), 'Unknown') size_bytes = int(message.get('sizeEstimate', 0)) size_mb = size_bytes / 1024 / 1024 return { 'subject': subject, 'from': sender, 'date': date_str, 'size_bytes': size_bytes, 'size_mb': size_mb } except Exception as e: print(f"Error: {e}") return None def main(): print("=" * 100) print("📧 OLD EMAILS REPORT") print("=" * 100 + "\n") # Load config config = Config() if not config.validate(): return False # Connect to Gmail service = get_gmail_service() # Find old emails print(f"Searching for emails older than {config.days_old} days...\n") emails = find_old_emails(service, config.days_old, limit=10) if not emails: print("✅ No old emails found!") return True # Get details for each print(f"{'Subject':<40} {'From':<30} {'Size (MB)':<10}") print("-" * 100) total_size_mb = 0 for email in emails: details = get_email_details(service, email['id']) if details: print(f"{details['subject'][:40]:<40} {details['from'][:30]:<30} {details['size_mb']:>8.2f}") total_size_mb += details['size_mb'] print("-" * 100) print(f"Total: {len(emails)} emails, {total_size_mb:.2f} MB\n") return True if __name__ == "__main__": main() EXAMPLE OUTPUT ================================================================================ ==================================================================================================== 📧 OLD EMAILS REPORT ==================================================================================================== Searching for emails older than 365 days... ✅ Found 10 emails older than 365 days Subject From Size (MB) ---------------------------------------------------------------------------------------------------- Old Newsletter #1 newsletter@company.com 0.50 Promotional Email promo@store.com 1.20 Meeting Notes 2023 manager@work.com 0.75 Bank Statement bank@financial.com 0.30 Old Receipt receipt@shop.com 0.15 Newsletter Archive newsletter@site.com 0.45 Spam Email spam@unknown.com 2.10 Archived Conversation colleague@work.com 0.85 Marketing Campaign marketing@brand.com 0.60 Old Attachment friend@email.com 3.50 ---------------------------------------------------------------------------------------------------- Total: 10 emails, 10.40 MB KEY PATTERNS ================================================================================ ✅ Get message details from API ✅ Extract headers (subject, from, date) ✅ Calculate message size ✅ Format table output ✅ Calculate totals ✅ Error handling This is production-ready reporting! ================================================================================