Python实现Outlook未读邮件指定附件下载及标记已读问题求助
Hey there! Awesome work getting this far with your first practical Python script—building tools that solve real problems is such a satisfying milestone. Let's tackle those two issues you're facing one by one.
Issue 1: Duplicate Attachments Getting Overwritten
The problem here is that your date_time_stamp is generated once at the start of the script, so every attachment gets the same timestamp. That means if you download multiple attachments in the same run, they'll still overwrite each other.
To fix this, we need to generate a unique identifier for each attachment. A simple, effective approach is to generate a new timestamp each time you save an attachment. We can also avoid hardcoding the file extension by using the original attachment's filename and extension, making the script more flexible.
Issue 2: Marking Emails as Read
This one is straightforward! Outlook's Message object has an Unread property—simply set it to False after you've successfully downloaded the target attachment.
Bonus Fix: Avoid Skipping Emails
Your current loop uses message = subfolderitems.GetNext() inside the for loop, which will cause you to skip some emails because the for loop is already iterating through the items automatically. We can remove that line entirely to prevent this.
Modified Full Code
import win32com.client import os import time # Set custom working directory save_dir = 'C:\\Users\\user_name\\Desktop\\' os.chdir(save_dir) print(f"Working directory set to: {os.getcwd()}") outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") main_inbox = outlook.GetDefaultFolder(6) subfolder = main_inbox.Folders.Item("my_child_folder_under_inbox") subfolder_items = subfolder.Items target_attachment_name = 'my_attachment_name' # Loop through messages in the subfolder for message in subfolder_items: if message.Unread: print("New unread mail found... Checking for target attachment...") attachment_saved = False for attachment in message.Attachments: if attachment.Filename == target_attachment_name: # Generate a unique timestamp for this specific attachment timestamp = time.strftime("%Y%m%d-%H%M%S") # Split original filename and extension to preserve format file_base, file_ext = os.path.splitext(attachment.Filename) # Create a unique save path using the original name + timestamp save_path = os.path.join(save_dir, f"{file_base}_{timestamp}{file_ext}") # Save the attachment attachment.SaveASFile(save_path) print(f"Successfully saved attachment to: {save_path}") attachment_saved = True break # Mark the email as read ONLY if we found and saved the target attachment if attachment_saved: message.Unread = False print("Marked email as read.\n") else: print("Target attachment not found in this email.\n") else: print("Skipping already read email...\n")
Key Changes Explained:
- Unique Filenames: We generate a new
timestampinside the attachment loop, so each saved file gets a distinct name. We also useos.path.splitextto keep the original file extension instead of hardcoding.csv. - Conditional Read Marking: Added
message.Unread = Falseonly after confirming the target attachment was saved, so we don't mark emails without the attachment as read. - Cleaner Iteration: Removed the manual
GetNext()call since theforloop handles traversing the folder items automatically. - Clearer Feedback: Added more descriptive print statements to track exactly what's happening with each email.
Give this modified code a try—it should resolve both your issues. Let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者Sakthi Ganesh

