I'm trying to download emails and pdf attachments for a certain time range but when trying to run it in Python, I'm receiving the error: "AttributeError: '<win32com.gen_py.Microsoft Outlook 16.0 Object Library._Application instance at 0x1796763072736>' object has no attribute 'GetNameSpace'"
It used to work last week but not sure what went wrong with the code since I haven't touched it either. Sharing my entire code below.
import win32com.client
import os
import time
import datetime as dt
import re
DateFilter = dt.datetime.now() - dt.timedelta(days = 2)
#Outlook MAPI
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
#Inbox Folder
inbox = outlook.GetDefaultFolder(6)
#Download Path
path = os.path.expanduser("~\Desktop")
#Sort emails in inbox
messages = inbox.Items
messages.Sort("[ReceivedTime]", True)
#Filter emails to go through
DateFilterMsg = messages.Restrict("[ReceivedTime] >= '" + DateFilter.strftime('%m/%d/%Y %H:%M %p')+"'")
for message in DateFilterMsg:
#Saving pdf attachments and their emails
for attachment in message.attachments:
if attachment.FileName.find(".pdf") > -1:
attachment.SaveAsFile(f"{path}\Email Downloader\attachments\{attachment.FileName}")
emailname = str(message.subject)
emailname = re.sub('[^A-Za-z0-9]+', ' ', emailname)
print(emailname)
mailName = f"{path}\Email Downloader\emails\{emailname}.msg"
message.SaveAs(mailName)
question from:
https://stackoverflow.com/questions/65890196/how-to-clear-the-attributeerror-for-win32com-of-object-has-no-attribute-getnam 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…