================================================================================ GMAIL CLEANUP - CHALLENGE 2 SOLUTION Chapter 6: Generalization & Extension Challenge: Archive Instead of Delete ================================================================================ PROBLEM: Create version that archives instead: 1. Archive old emails to archive folder 2. Keep in Gmail but hidden 3. Report storage saved 4. Make it reversible SOLUTION: ================================================================================ File: cleanup_archive.py class GmailArchive(GmailCleanup): """Archive emails instead of deleting.""" def archive_email(self, message_id: str) -> bool: """Archive email (remove from INBOX).""" try: self.service.users().messages().modify( userId='me', id=message_id, body={'removeLabelIds': ['INBOX']} # Remove from inbox ).execute() self.archived_count += 1 return True except Exception as e: print(f"Error: {e}") return False def unarchive_email(self, message_id: str) -> bool: """Restore email to INBOX.""" try: self.service.users().messages().modify( userId='me', id=message_id, body={'addLabelIds': ['INBOX']} # Add back to inbox ).execute() self.archived_count -= 1 return True except Exception as e: print(f"Error: {e}") return False def add_custom_label(self, message_id: str, label: str) -> bool: """Add custom label (for organization).""" try: self.service.users().messages().modify( userId='me', id=message_id, body={'addLabelIds': [label]} ).execute() return True except Exception as e: print(f"Error: {e}") return False USAGE ================================================================================ from gmail_utils import get_gmail_service from cleanup_archive import GmailArchive service = get_gmail_service() archive = GmailArchive(service, config) # Find old emails emails = archive.find_old_emails(days=365) # Archive instead of delete for email in emails: archive.archive_email(email['id']) print(f"Archived: {archive.archived_count}") # If needed, restore # archive.unarchive_email(email_id) BENEFITS VS DELETION ================================================================================ Archive: ✅ Reversible (can restore if needed) ✅ Still searchable in "All Mail" ✅ Less risky ✅ Can organize with labels ✅ Safer for important info Delete: ✅ Actually frees storage ✅ Not in search results ✅ Cleaner inbox ================================================================================