使用Python win32com读取Outlook多邮箱收件箱获取发件人地址
Hey there, let's get this sorted out! The issue you're facing is that GetDefaultFolder(6) only targets the default mailbox in your Outlook profile. To access other mailboxes, you need to first locate the root folder of each target mailbox from outlook.Folders, then retrieve its inbox. Here's a step-by-step solution:
Step 1: Locate the Target Mailbox Root Folder
Each mailbox in Outlook appears as a top-level folder under outlook.Folders. We can loop through these folders to match your target email addresses. Note: Some mailboxes might show a display name instead of the raw email address—if that's the case, adjust the matching logic to use folder.Name instead of folder.Session.CurrentUser.Address.
Step 2: Retrieve the Inbox for Each Mailbox
Once you have the root folder of a mailbox, use its GetDefaultFolder(6) method (6 is the constant for the Inbox folder) to access its inbox—this is different from calling GetDefaultFolder(6) directly on the MAPI namespace, which only gets the default mailbox's inbox.
Step 3: Extract Sender Email Addresses
Loop through all items in the inbox, collect the SenderEmailAddress property, and handle cases where this property might be missing (e.g., meeting requests).
Step 4: Save to CSV
Use Python's built-in csv module to write the collected addresses to a CSV file.
Full Working Code
import win32com.client import csv def get_target_mailbox(outlook, target_email): """Locate the root folder of the target mailbox""" for folder in outlook.Folders: # Match by the mailbox's email address if folder.Session.CurrentUser.Address == target_email: return folder # Optional: If mailbox uses a display name instead, uncomment below # if folder.Name == "Your Mailbox Display Name": # return folder return None def extract_sender_addresses(inbox): """Extract SenderEmailAddress from all emails in the inbox""" senders = set() # Use a set to avoid duplicate addresses for item in inbox.Items: # Skip non-mail items (like meetings, tasks) if item.Class == 43: # 43 is the constant for MailItem try: sender_addr = item.SenderEmailAddress if sender_addr: senders.add(sender_addr) except Exception as e: print(f"Error processing item: {str(e)}") return sorted(senders) if __name__ == "__main__": # Initialize Outlook outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Define your target mailboxes target_emails = ["123@abc.com", "456@def.com"] all_senders = set() # Process each mailbox for email in target_emails: mailbox = get_target_mailbox(outlook, email) if not mailbox: print(f"Warning: Could not find mailbox for {email}") continue # Get the inbox of the target mailbox inbox = mailbox.GetDefaultFolder(6) print(f"Processing {email} Inbox - {len(inbox.Items)} items found") # Extract sender addresses mailbox_senders = extract_sender_addresses(inbox) all_senders.update(mailbox_senders) # Save to CSV output_file = "outlook_sender_addresses.csv" with open(output_file, "w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow(["SenderEmailAddress"]) # Header row for addr in sorted(all_senders): writer.writerow([addr]) print(f"Success! Saved {len(all_senders)} unique sender addresses to {output_file}")
Key Fixes from Your Original Code
- Instead of trying to access mailboxes as subfolders of the default inbox, we directly access them as top-level folders in
outlook.Folders. - Using
mailbox.GetDefaultFolder(6)ensures we get the inbox of the specific mailbox, not the default one. - Added error handling and filtering for non-mail items to avoid crashes.
Notes
- Make sure Outlook is running (or open in the background) when you run this script.
- If your mailboxes use display names instead of email addresses as their folder names, update the
get_target_mailboxfunction to matchfolder.Nameinstead offolder.Session.CurrentUser.Address. - For large inboxes, you might want to add pagination or batch processing to avoid performance issues, but the code above works for most use cases.
内容的提问来源于stack exchange,提问作者David G

