使用Exchangelib:读取最新邮件、提取附件并移至指定文件夹
Solution: Fetch Latest Email, Save Attachments, and Move to Target Folder
You're already halfway there with your attachment-saving code! Let's extend it to include moving the processed email to your desired folder. Here's the complete, working implementation:
from exchangelib import Credentials, Account import os # Set up credentials and account connection credentials = Credentials('test.name@mail.com', 'password') account = Account('test.name@mail.com', credentials=credentials, autodiscover=True) # Define your local attachment save path and target mailbox folder attachment_save_path = "C:/destination_folder_for_attachments" target_folder_name = "Processed Emails" # Replace with your actual folder name # Ensure the local save directory exists (no error if it already does) os.makedirs(attachment_save_path, exist_ok=True) # Grab the most recently received email from your inbox latest_email = account.inbox.all().order_by('-datetime_received')[0] # Save all valid attachments to your local path for attachment in latest_email.attachments: # Skip inline attachments (like signature images) unless you want to keep them if hasattr(attachment, 'content'): full_file_path = os.path.join(attachment_save_path, attachment.name) with open(full_file_path, 'wb') as file: file.write(attachment.content) print(f"Successfully saved: {full_file_path}") # Locate your target mailbox folder # Use this if the folder is a direct child of your inbox: target_folder = account.inbox / target_folder_name # If it's a top-level folder (not under inbox), use this instead: # target_folder = account.root / target_folder_name # Move the processed email to the target folder latest_email.move(target_folder) print(f"Email moved to folder: {target_folder.name}")
Quick Tips for Production Use:
- Folder Validation: Add a check to confirm the target folder exists before trying to move the email (wrap the folder lookup in a
try/exceptblock to handle missing folders gracefully). - Inline Attachments: Remove the
hasattr(attachment, 'content')check if you want to save every attachment, including images embedded in the email body. - Error Handling: Add try/except blocks around file writes and email moves to catch issues like permission errors or connection drops.
内容的提问来源于stack exchange,提问作者O. Schultz
相关产品推荐
相关产品推荐

