Reputation: 11
I am writing a python code to download a specific attachment from unread emails in outlook and mark those emails as read. I have managed to finish 90% of it i.e. I can do an iteration to open unread emails and download the attachments with a specific emails. However, I have two issues.
I am downloading the attachment with the same name, and if there are two attachments with the same name, it just saves the one it extracts from the last iteration. I tried appending a time stamp at the end of the file name but it has the same effect. Any help would be appreciated. This is not mandatory requirement since the mail comes at stipulated intervals and I can write a separate python code to rename it but I want to pack everything in this single email.
I would like to mark the email as read after the attachment is downloaded. I do not know the command for this one. I have attached the code for your reference.
P.S. This is my first real python code. Also this is my first post here. Apologies if this is was already asked elsewhere.
import win32com.client
import os
import time
date_time_stamp = time.strftime("%Y%m%d-%H%M%S")
#set custom working directory
os.chdir('C:\\Users\user_name\Desktop\')
print(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")
subfolderitems = subfolder.Items
message = subfolderitems.GetFirst()
attachment_name = 'my_attachment_name'
#Loop to pick messages that are unread
for message in subfolderitems:
if message.Unread == True:
print("New Mail Found... Downloading Attachment...")
#Loop to check if the attachment name is the same
for attachments in message.Attachments:
if attachments.Filename == attachment_name:
#Saves to the attachment to the working directory
attachments.SaveASFile(os.getcwd() + '\\' + 'my_attachment_name' + date_time_stamp + '.csv')
print (attachments)
time.sleep(2)
break
#Go to next unread messages if any
message = subfolderitems.GetNext()
else:
print ("Checking...")
-- Thanks and Regards, Sakthi Ganesh K.
Upvotes: 1
Views: 8446
Reputation: 8077
I think it may have to do with your 'date_time_stamp', since it tries to download the files in the same second, and the system only keeps the last one. You could try using a UUID for that to ensure it is a unique string:
import uuid
file_uuid = str(uuid.uuid4())
...
attachments.SaveASFile(os.getcwd() + '\\' + 'my_attachment_name' + file_uuid + '.csv')
To mark the message as Read, you could simply do:
message.Unread = False
message.Save()
Upvotes: 9