使用win32com.client操作Outlook保存附件遇权限错误求助
解决Outlook附件保存的com_error权限问题
报错信息
An exception occurred: com_error (-2147352567, 'Exception.', (4096, 'Microsoft Outlook', 'Cannot save attachment. You do not have the proper permissions to perform this operation.', None, 0, -2147024891), None) File "C:\Users\jec\OneDrive - XP Investimentos\Financeiro\X - Teste\Automações\500000\Automation.py", line 17, in <module> pdf.SaveAsFile(str(pdf)) pywintypes.com_error: (-2147352567, 'Exception.', (4096, 'Microsoft Outlook', 'Unable to save attachment. You do not have the proper permissions to perform this operation.', None, 0, -2147024891), None)
葡萄牙语版本报错:
pywintypes.com_error: (-2147352567, 'Exceção.', (4096, 'Microsoft Outlook', 'Não é possível salvar o anexo. Você não possui a permissão adequada para executar esta operação.', None, 0, -2147024891), None)
相关代码
import win32com.client as client # python -m pip install --upgrade pywin32 import datetime as datetime import pandas as pd ## Connect in outlook outlook = client.Dispatch("Outlook.Application").GetNamesPace('MAPI') # 注意:此处存在拼写错误,正确应为 GetNamespace('MAPI') account = outlook.Folders['financeiro@manchesterinvest.com.br'] # Set the account inbox = account.Folders['INVESTIMENTO CONTAS A PAGAR'] # Select a folder ## Recover the invoice BHS_email = [message for message in inbox.Items if message.SenderEmailAddress == 'email@test.com.br' and int(pd.to_datetime(message.ReceivedTime, utc = True).strftime("%m")) == int(datetime.date.today().month)] # Only recovers the e-mail from the month (!!!! - CAN RECOVER THE EMAILS FROM THE SAME MONTH IN OTHER YEARS - !!!!) for message in BHS_email: attachment = message.Attachments for pdf in attachment: pdf.SaveAsFile(str(pdf))
注意:代码中GetNamesPace('MAPI')是拼写错误,正确写法为GetNamespace('MAPI'),否则会导致Outlook连接失败。
解决方法
指定完整保存路径:仅传入文件名时,Outlook会默认保存到其内部存储路径,该路径可能无写入权限。需明确指定有读写权限的路径(如桌面、自定义文件夹):
import os # 示例:保存到用户桌面 save_dir = os.path.join(os.path.expanduser("~"), "Desktop") # 确保目标文件夹存在 if not os.path.exists(save_dir): os.makedirs(save_dir) for message in BHS_email: for pdf in message.Attachments: save_path = os.path.join(save_dir, pdf.FileName) pdf.SaveAsFile(save_path)以管理员身份运行脚本:右键点击Python脚本或运行脚本的终端,选择「以管理员身份运行」,规避系统级权限限制。
检查Outlook信任设置:
- 打开Outlook,依次进入「文件」→「选项」→「信任中心」→「信任中心设置」→「附件处理」
- 取消勾选「禁用所有附件的预览」(若已勾选),确保PDF附件未被系统阻止
- 确认Outlook未在安全模式下运行(安全模式会限制部分操作权限)
验证目标文件夹权限:
- 右键要保存附件的文件夹,选择「属性」→「安全」标签
- 检查当前用户是否拥有「写入」「修改」权限,缺失则点击「编辑」添加对应权限
修复Outlook安装:若上述方法无效,可能是Outlook组件损坏:
- 打开控制面板→「程序和功能」,找到Microsoft Office/Outlook
- 右键选择「更改」,选择「快速修复」或「联机修复」,完成后重启Outlook重试
内容的提问来源于stack exchange,提问作者Caio Pavesi
相关产品推荐
相关产品推荐

