Reputation: 141
I want to save all my email messages from the inbox folder of outlook using Python. I can save the First or the last messages but couldn't understand how to get all the messages of the folder. Hence, I was trying to use a loop to iterate the code for all mails. I have tried to use the following code:
from win32com.client import Dispatch
import os
import re
os.chdir("D:\\emails")
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
print(inbox)
messages = inbox.items
message = messages.GetLast()
name = str(message.subject)
name = re.sub('[^A-Za-z0-9]+', '', name)+'.msg'
for message in messages:
message.SaveAs(os.getcwd()+'//'+name)
This is not giving me any errors, but saving only the last mail, instead of saving all emails. Could you please help me to rectify the code. Thanks.
Upvotes: 0
Views: 3352
Reputation: 141
The full code would look something like this.... (I got this answer from balderman)
from win32com.client import Dispatch
import os
import re
os.chdir("D:\\email")
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.items
for message in messages:
message = messages.GetNext()
name = str(message.subject)
name = re.sub('[^A-Za-z0-9]+', '', name)+'.msg'
message.SaveAs(os.getcwd()+'//'+name)
Upvotes: 0
Reputation: 23815
The problem is below
message = messages.GetLast()
name = str(message.subject)
and
message.SaveAs(os.getcwd()+'//'+name)
You calculate the name once (before the loop) and use it in the loop.
You need to calculate the name during the loop.
Upvotes: 2