python - (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)
我的问题是为什么会抛出这个错误?它有时可以正常工作,但大多数时候会抛出此错误。知道我的代码到底有什么问题吗?还是前景的问题?
根据我的理解,我认为 pywin 客户端无法获取列表中的文件夹。但不确定是不是这个原因。
解决方案
我注意到代码中有以下循环:
for i in range(rootFolder.Items.Count-1,0,-1):
msg = rootFolder.Items[i]
移动项目时,集合中的项目数会减少。所以,你需要为此做好准备。
此外,如果您只想移动与条件相对应的项目,则需要使用Find
/FindNext
或Restrict
方法来获取此类项目,并且它们会移动所有这些项目而不检查任何其他属性。在以下文章中阅读有关这些方法的更多信息:
推荐阅读
- asp.net-mvc - 检索 DateTime 对象时出现 ActionResult 异常
- react-redux - 如何做 redux-saga 结合测试和 jest 和酶
- conv-neural-network - 带有水印图像的 CNN 对象检测和训练,它会起作用吗?
- php - 如何从同一浏览器将一个域的相同 cookie 收集到另一个域?
- python - Python del sys.modules 触发的问题
- python - 删除超过 182.5 天的文件 [删除几年前新复制的文件]
- python - 如何在 for 循环中连接这些字符串变量?
- python - 安装了 Anaconda 但安装 flake8 后没有名为“conda”的模块
- node.js - 使用服务使用 Angular 7 迭代 json
- nginx - nginx缓存过早清空