【发布时间】:2022-11-10 22:32:59
【问题描述】:
我正在遍历存储在数据框中(从 csv 文件加载)中的 entryId,并通过调度 win32com.client 访问 Outlook MAPI 并使用以下代码将电子邮件附件保存到本地目录来访问消息。我还将附件名称、路径和 entryId 存储在一个新的数据框中以供以后分析。
- Outlook 版本:2202(内部版本 14931.20764)
- Pywin32 版本:227
- Python 版本:3.7.1
df = pd.DataFrame(columns=['attName', 'path', 'entryId'])
id = 1
for email in emailData.itertuples():
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
message = outlook.GetItemFromID(email.entryId)
if message:
receivedDate = message.ReceivedTime
if message.Attachments.Count > 0:
for attachment in message.Attachments:
if attachment.Type in {1,4,5}:
if not attachment.DisplayName.endswith('.png') and not attachment.DisplayName.endswith('.jpg') and not attachment.DisplayName.endswith('.gif'):
attName = str(attachment.DisplayName)
print('\t Attachment: %s' % attachment.DisplayName)
path = "some directory\\%s\\%s" % (receivedDate.year, attachment.DisplayName)
attachment.SaveAsFile(path) #if I remove this line, the error no longer occurs
attachment = None
df.loc[id] = ([attName, str(path), email.entryId])
id += 1
attachments = None
message.Close(1)
outlook.Logoff()
outlook = None
扫描 248 条消息后,无论特定消息如何,都会遇到以下错误:
File "C:\Anaconda3\envs\myenv\lib\site-packages\win32com\client\__init__.py", line 474, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Anaconda3\envs\myenv\lib\site-packages\win32com\client\__init__.py", line 467, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, 'Microsoft Outlook', 'Your server administrator has limited the number of items you can open simultaneously. Try closing messages you have opened or removing attachments and images from unsent messages you are composing.', None, 0, -2147220731), None)
我能够将错误专门隔离到这一行:
attachment.SaveAsFile(path)
如果我删除此行,错误就会消失,并将继续扫描消息。我不确定是什么导致了这个错误,我尝试了各种命令来关闭/删除对附件的引用,方法是将对象设置为 None 并使用 outlook.Logoff() 作为命名空间。
有没有其他人遇到过这个问题或有什么办法解决它?
更新:在阅读了Eugene Astafiev 的有用建议后,我对我的代码进行了一些更新,以帮助表明问题出在 attachment.SaveAsFile(path) 行上。不幸的是,我仍然收到完全相同的错误。也许我不明白如何释放对象?任何人都可以提供进一步的帮助吗?
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
for email in emailData.itertuples():
message = outlook.GetItemFromID(email.entryId)
if message:
attachments = []
for attachment in list(message.Attachments):
attachments.append(attachment)
for attachment in attachments:
attachType = int(attachment.Type)
if attachType in {1,4,5}:
attName = str(attachment.DisplayName)
if not attName.endswith('.png') and not attName.endswith('.jpg') and not attName.endswith('.gif'):
path = "somedir\\%s" % (attName)
attachment.SaveAsFile(path) #Error disappears if this line is removed
del attachment
del path
del attName
del attachType
del attachments
message.Close(1)
del message
【问题讨论】:
标签: python outlook win32com mapi office-automation