如何通过Python和IMAP删除2-3天前的邮件?(Google Takeout场景)
Solution for Targeted Email Deletion via IMAP
Got it, let's adjust your script to only delete emails that are 2-3 days old—perfect for your Google Takeout backup workflow. Here's how to make it happen:
Key Background: IMAP Date Filtering
IMAP uses a specific date format (DD-MMM-YYYY, uppercase month abbreviations) for search queries. We'll use the SINCE and BEFORE operators to target emails that fall exactly in the 2-3 day window you need.
Modified Script
First, add the datetime imports to calculate the date range, then update the IMAP search criteria:
from datetime import datetime, timedelta import imaplib import time def deleteEmailIMAP(user, password, IMAP): mail = imaplib.IMAP4_SSL(IMAP) mail.login(user, password) print("Logging into account:", user ) mail.select("Process") # Select your target folder/label print("Process Folder Selected") time.sleep(2) # Calculate the date range: 3 days ago (inclusive) to 2 days ago (exclusive) three_days_ago = datetime.now() - timedelta(days=3) two_days_ago = datetime.now() - timedelta(days=2) # Convert dates to IMAP's required format (DD-MMM-YYYY, uppercase) imap_three_days = three_days_ago.strftime("%d-%b-%Y").upper() imap_two_days = two_days_ago.strftime("%d-%b-%Y").upper() # Build the search criteria: emails received between 3-2 days ago search_criteria = f'(SINCE "{imap_three_days}" BEFORE "{imap_two_days}")' typ, data = mail.search(None, search_criteria) if not data[0]: print("No matching emails found in the 2-3 day window.") else: print(f"Found {len(data[0].split())} emails from the 2-3 day window to move to Trash.") for num in data[0].split(): mail.store(num, '+X-GM-LABELS', r'(\Trash)') # Move to trash and remove from folder mail.expunge() print("Selected emails sent to Trash.") print("Emptying Trash & Expunge...") mail.select('[Gmail]/Trash') # Select the Trash folder mail.store("1:*", '+FLAGS', '\Deleted') # Flag all trash items for deletion mail.expunge() # Skip if auto-expunge is enabled in your Gmail settings print("Done. Closing connection & logging out.") time.sleep(2) mail.close() mail.logout() # Call the function with your credentials deleteEmailIMAP(email, passw, imapserver)
Important Notes:
- Timezone Consideration: If your Gmail account uses UTC or a different timezone than your local machine, replace
datetime.now()withdatetime.utcnow()to match server timestamps. - Search Logic:
SINCEincludes the start date,BEFOREexcludes the end date—this ensures we only target emails that are strictly 2-3 days old (e.g., if today is Oct 10, we get emails from Oct 7 to Oct 8). - Safety Check: The script now checks if there are any matching emails before proceeding, so you won't accidentally run unnecessary operations.
内容的提问来源于stack exchange,提问作者Dilshan
相关产品推荐
相关产品推荐

