编辑:解决了!
我在下面添加了这段代码,以便跟踪主收件箱文件夹的位置
对于 Outlook.Folders 中的文件夹: 打印(文件夹)
这突显了基础 Outlook 结构中发生了某些变化,并且文件夹[0] 不再有效。我现在将调整代码以使其更加健壮并动态选择文件夹
编辑结束
我编写了一些代码来从 Outlook 中提取电子邮件并保存附件。直到几天前它都运行良好。
我没有接触过代码,所以我只能假设 Outlook 中的某些内容发生了变化。我在公司环境工作,所以有软件的远程更新。
有人知道这个错误是什么意思以及为什么突然出现吗?我非常沮丧,因为在出现这个问题之前代码运行得很好。或者,是否有更好的方法使用 Python 从 Outlook 检索电子邮件和附件?
import win32com.client
def main():
pass
def saveAttachments():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI") # Opens Microsoft Outlook
mailbox = outlook.Folders[0] # Based off email address
inbox = mailbox.Folders["Inbox"]
emails = inbox.Items
emails.Sort("[ReceivedTime]", True)
destPath = "\\\\servername\\path\\"
try:
for mail in emails:
if ("Detailed MTM," in mail.subject) and (mail.Attachments.Count > 0):
print(mail.Sender)
print(mail.Subject)
print(mail.Receivedtime)
attachments = mail.Attachments
for file in attachments:
if "MTMDetailed" in str(file):
file.SaveAsFile(destPath + str("MTMDetailed.xls"))
break
except:
file = open(destPath + "error.log", "w")
file.write("Problem")
file.close()
if __name__ == '__main__':
main()
saveAttachments()
<小时/>
File "C:\Tools\Python\lib\site-packages\win32com\client\dynamic.py", line 256, in __getitem__
return self._get_good_object_(self._oleobj_.Invoke(dispid, LCID, invkind, 1, index))
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed. An object could not be found.', None, 0, -2147221233), None)
最佳答案
我添加了代码来迭代 Outlook.Folders 以找到我需要的文件夹,而不依赖于特定的硬编码位置
关于python - 使用 Python 和 win32com 从 Outlook 检索电子邮件时突然出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56372040/