Please help a beginner python student out! I would really appreciate it.
I am trying to automatically filter emails from my inbox and save them as a text document in a specified folder. I can get the emails in my folder as .msg no problem, however, when I try to save it as a .txt file it either a) does not open up normally when I remove 'olTXT' or b) throws me the following error when I add 'olTXT':
line 19, in <module>
message.SaveAs(os.getcwd()+'//'+name, olTXT)
NameError: name 'olTXT' is not defined
I am using https://learn.microsoft.com/en-us/office/vba/api/outlook.mailitem.saveas as my reference.
This is what I have so far:
import win32com.client
from win32com.client import Dispatch
import os
import re
outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.items
message = messages.GetFirst()
report_subject = "Tech Report"
for message in messages:
if message.subject[0:11] == report_subject:
name = str(message.subject)
#to eliminate any special charecters in the name
name = re.sub('[^A-Za-z0-9]+', '', name)+'.txt'
#to save in the current working directory
message.SaveAs(os.getcwd()+'//'+name, olTXT)
Try adding this:
OlSaveAsType = {
"olTXT": 0,
"olRTF": 1,
"olTemplate": 2,
"olMSG": 3,
"olDoc": 4,
"olHTML": 5,
"olVCard": 6,
"olVCal": 7,
"olICal": 8
}
# example
message.SaveAs(os.getcwd()+'//'+name, OlSaveAsType['olTXT'])
Reference: Outlook.OlSaveAsType.olMSG
The way you have it now you are referencing a variable olTXT before it is ever assigned which is why you are receiving the error.