尝试使用 win32com.client 过滤某个主题的 Outlook 邮件时,如何修复 com 错误 -2147221005“无效的类字符串”?

问题描述 投票:0回答:1

我试图从 Outlook 下载满足特定主题的附件,但出现异常,不知道如何更正我的代码。下面是我的代码:

import win32com.client
import os
get_path = os.getcwd()
outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
message2 = messages.GetLast()
subject = message2.Subject
body = message2.body
sender = message2.Sender
attachments = message2.Attachments
for m in messages:
    if m.Subject == "Test Mail":
        for x in message2.Attachments:
            x.SaveASFile(os.path.join(get_path,x.FileName))
            print "successfully downloaded attachments"

问题来了:

Traceback (most recent call last):
  File "C:/Users/LENOVO USER/PycharmProjects/FlaskProject/EmailFilter/TestFile.py", line 4, in <module>
    outlook = win32com.client.Dispatch("Outlook.Application").GetNameSpace("MAPI")
  File "C:\Python27\lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch
    dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 114, in _GetGoodDispatchAndUserName
    return (_GetGoodDispatch(IDispatch, clsctx), userName)
  File "C:\Python27\lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatch
    IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221005, 'Invalid class string', None, None)
python outlook attachment win32com
1个回答
2
投票

如回溯所示,错误位于您定义

outlook
的行。实际上,
GetNamespace
中没有大写S,因此将此行替换为:

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

但是会出现其他错误,在定义

body
的行,该属性必须有一个上限,例如
body = message2.Body
,而
x.SaveASFile
中的另一个上限问题,应该是
x.SaveAsFile

最后,当您尝试下载

message2
的附件(这是您的最后一条消息)时,我不确定您的代码是否会执行您所描述的操作,而您则迭代
messages
,那么我不明白这一点。

如果您需要更多帮助或者我是否误解了您的问题,请告诉我。

© www.soinside.com 2019 - 2024. All rights reserved.