检索 Outlook 电子邮件时出现'Cannot save the attachment'错误



截至今天,我在尝试使用Python和win32com库从Outlook保存电子邮件附件时收到一个错误。然而,这在以前是有效的,因为修改代码只获取最新的电子邮件,附件不再保存到指定的位置。

请参阅下面的代码和注释。

## Dependencies
import win32com.client
import os
from datetime import datetime, timedelta
## Aliases
outlook = win32com.client.Dispatch('outlook.application')
mapi = outlook.GetNamespace("MAPI")
## Get accounts
for account in mapi.Accounts:
print(account.DeliveryStore.DisplayName)
## Date parameters for filter
today = datetime.today()
start_time = today.replace(day=7).strftime('%Y-%m-%d %H:%M %p')
end_time = today.replace(hour=0, minute=0, second=0).strftime('%Y-%m-%d %H:%M %p')
## Retrieve mail
messages = mapi.Folders('me@my_email_address.com').Folders('Inbox').Items.Restrict("[ReceivedTime] >= '" + start_time
+ "' And [ReceivedTime] <= '" + end_time + "'")
messages = messages.Restrict("[Subject] = 'Really cool email'")
## Check output
for message in messages:
print(message ,  "|" , message.ReceivedTime, "|",  attachment.FileName)

最后一步显示以下内容。请注意,存在电子邮件附件。

'FW: Really cool email | 2022-07-11 04:04:09.866000+00:00 | Really cool attachment.xlsx'
'FW: Really cool email | 2022-07-18 03:53:51.475000+00:00 | Really cool attachment.xlsx'

在下一步中,我遍历消息,以便提取附件并将其保存到我指定的位置。

## Specify file destination path
outputDir = r"Z:My FolderReally Cool Data Folder"
## Save attachments
try:
for message in list(messages):
try:
s = outputDir
for attachment in message.Attachments:
attachment.SaveASFile(os.path.join(outputDir, attachment.FileName))
print(f"attachment {attachment.FileName} saved to {s} '")
except Exception as e:
print("error when saving the attachment:" + str(e))
except Exception as e:
print("error when processing emails messages:" + str(e))

我现在得到的错误是;

error when saving the attachment:
(-2147352567, 'Exception occurred.',
(4096, 'Microsoft Outlook', 'Cannot save the attachment.', None, 0,
-2147024864), None)

我一直无法理解为什么附件无法保存。如上所述,在添加一些过滤以提高循环效率之前,此代码的工作方式与预期一致。

请注意,该错误没有提及任何有关权限或无效文件路径的信息。

-2147024864(0x80070020(转换为ERROR_SHARING_VIOLATION,这意味着正在使用您试图覆盖的文件。

请确保关闭Excel或至少关闭要覆盖的xlsx文件。

相关内容

最新更新