首页 > 解决方案 > (4096, 'Microsoft Outlook', '尝试的操作失败。找不到对象。', None, 0, -2147221233), None) - Outlook 中的错误

问题描述

我目前正在使用 pywin32.com python 库将邮件移动到 Outlook 中的特定文件夹。我必须使文件夹路径可配置,因此我创建了一个 python 文件,将文件夹路径保存为列表。FoldersConfig.py 文件的内容是:

#相对于收件箱文件夹的文件夹名称

mailBox = "mailbox-name"
nagiosDestinationFolder = ["Resolved_Clients","Internal","Nagios alerts"] #all these folders are been created in outlook with exact names.

然后还有另一个文件可以将邮件移动到目标文件夹。在我的例子中, Nagios alerts是我的目标文件夹。MoveNagiosAlerts.py 文件的代码片段是:

outlook = client.Dispatch("Outlook.Application").GetNamespace("MAPI")
    stores = outlook.Stores
    for store in stores:
        mailBox = FoldersConfig.mailBox
        if(mailBox in store.DisplayName):
            rootFolder = store.GetDefaultFolder(6) #rootFolder is the Inbox folder
            break 
    
    def moveWarnings():
        print("Moving warning mails...")
        warnCount = 0
        scriptingDictionary = {}
        nagiosDestFolder = rootFolder
        for i in FoldersConfig.nagiosDestinationFolder:
            nagiosDestFolder = nagiosDestFolder.Folders(i)
        print(nagiosDestFolder)
        for i in range(rootFolder.Items.Count-1,0,-1):
            msg = rootFolder.Items[i]
            if(msg.Body.find("State: WARNING") != -1):
               msg.Move(nagiosDestFolder)
               warnCount+=1
        return warnCount

运行 MoveNagiosAlerts.py 文件时弹出的错误是:

Root folder(Inbox):  Inbox
Moving warning mails..
Traceback (most recent call last):
  File "C:\Users\Documents\MoveNagiosAlerts.py", line 193, in <module>
    main()
  File "C:\Users\Documents\MoveNagiosAlerts.py", line 172, in main
    warningsCount = moveWarnings()
  File "C:\Users\Documents\MoveNagiosAlerts.py", line 56, in moveWarnings
    nagiosDestFolder = nagiosDestFolder.Folders(i)
  File "C:\Users\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages\win32com\client\dynamic.py", line 181, in __call__
     return self._get_good_object_(self._oleobj_.Invoke(*allArgs),self._olerepr_.defaultDispatchName,None)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'The attempted operation failed.  An object could not be found.', None, 0, -2147221233), None)

供您参考的 Outlook 文件夹结构

我的问题是为什么会抛出这个错误?它有时可以正常工作,但大多数时候会抛出此错误。知道我的代码到底有什么问题吗?还是前景的问题?

根据我的理解,我认为 pywin 客户端无法获取列表中的文件夹。但不确定是不是这个原因。

标签: pythonoutlook

解决方案


我注意到代码中有以下循环:

for i in range(rootFolder.Items.Count-1,0,-1):
            msg = rootFolder.Items[i]

移动项目时,集合中的项目数会减少。所以,你需要为此做好准备。

此外,如果您只想移动与条件相对应的项目,则需要使用Find/FindNextRestrict方法来获取此类项目,并且它们会移动所有这些项目而不检查任何其他属性。在以下文章中阅读有关这些方法的更多信息:


推荐阅读