如何通过IMAP从Gmail获取指定标签的邮件ID?
Absolutely, you can fetch message IDs by labels like Update, Promotions, or Social using IMAP with Gmail—here's a step-by-step breakdown of how it works, since Gmail maps its labels directly to IMAP mailboxes:
How Gmail Labels Work with IMAP
Gmail treats every label (both system ones like Promotions/Social/Updates and your custom labels) as an IMAP "folder" (officially called a mailbox). System labels are typically prefixed with [Gmail] to distinguish them from custom labels.
Step-by-Step Implementation
Let’s walk through how to do this with Python’s built-in imaplib (the logic translates to other IMAP libraries too):
Connect and authenticate to Gmail's IMAP server
Gmail uses IMAP over SSL on port 993. If you have 2FA enabled (which you should), use an App Password instead of your regular password. If not, you can use your regular password (though App Passwords are far more secure).import imaplib # Initialize SSL connection imap = imaplib.IMAP4_SSL("imap.gmail.com", 993) # Authenticate imap.login("your-email@gmail.com", "your-app-password-or-regular-password")List available labels to confirm their IMAP names
Run this to see exactly how Gmail exposes your labels as IMAP mailboxes. System labels will show up as[Gmail]/Promotions,[Gmail]/Social, etc., while custom labels like "Update" will likely appear as just "Update".status, folders = imap.list() for folder in folders: print(folder.decode()) # Decode byte string to readable textSelect the target label's mailbox
Useimap.select()to open the mailbox corresponding to your label. Enclose the mailbox name in double quotes if it contains spaces or special characters (like the[Gmail]prefix).
Example for the Promotions label:# Select the Promotions mailbox status, message_count = imap.select('"[Gmail]/Promotions"') print(f"Found {message_count[0].decode()} messages in Promotions")For a custom "Update" label:
status, message_count = imap.select('"Update"')Fetch all message IDs in the label
Useimap.search()with theALLcriteria to get all message IDs in the selected mailbox. The result will be a list of byte strings you can decode and process.status, msg_id_bytes = imap.search(None, "ALL") # Split the byte string into individual message IDs message_ids = msg_id_bytes[0].split() # Print or process each ID for msg_id in message_ids: print(f"Message ID: {msg_id.decode()}")
Bonus: Use IMAP IDLE for real-time updates
Since you switched to IMAP for idle support, Gmail’s IMAP fully supports the IDLE command. Here’s a quick snippet to listen for new messages in a label:
# After selecting the mailbox imap.idle() print("Waiting for new messages...") # Wait for updates (timeout after 30 minutes, adjust as needed) status, updates = imap.idle_check(timeout=1800) if updates: print("New messages received!") # Re-fetch message IDs or process the updates imap.idle_done()
Important Notes
- Ensure IMAP is enabled in your Gmail settings: Go to Settings > Forwarding and POP/IMAP > Enable IMAP
- App Passwords: If 2FA is enabled, create one in your Google Account under Security > App Passwords (you’ll need to select "Mail" and your device)
- Case sensitivity: Mailbox names are case-insensitive in IMAP, but it’s safest to use the exact name from the
list()output
内容的提问来源于stack exchange,提问作者user9714409

