如何使用Python遍历Outlook非默认收件箱文件夹并下载附件
解决方案
问题根因
- 原
mapi.Folders('hhh@yyy.com').Folders('Inbox').Items写法失效的最常见原因是Outlook客户端本地化导致文件夹名称不匹配:例如中文环境下收件箱显示名称为「收件箱」,而非英文Inbox - 其他可能原因:账号拼写与实际挂载名称不符、COM组件权限不匹配
- 原代码还存在两处隐藏问题:连续两次调用
Restrict会覆盖前一次的筛选规则,且未导入os模块会导致保存附件时报错
步骤1:枚举确认正确的账号与文件夹名称
先运行以下代码,打印所有已绑定的账号名称,以及对应账号下的所有文件夹名称,获取准确的调用参数:
import win32com.client outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") # 遍历所有已挂载的账号 for account in mapi.Folders: print(f"账号名称:{account.Name}") # 遍历当前账号下的所有文件夹 for folder in account.Folders: print(f" 文件夹名称:{folder.Name}") print("-"*50)
运行后即可拿到目标账号的准确名称、以及该账号下收件箱的准确名称,替换后续代码中的对应参数即可。
步骤2:修正后的完整功能代码
import win32com.client import pendulum import os # 补充缺失的os模块导入 outlook = win32com.client.Dispatch('outlook.application') mapi = outlook.GetNamespace("MAPI") # 替换为步骤1中获取的目标账号名称、收件箱名称 target_account = "hhh@yyy.com" target_inbox = "收件箱" # 英文环境改为"Inbox" inbox = mapi.Folders(target_account).Folders(target_inbox) messages = inbox.Items # 构造筛选规则,合并时间和主题条件,避免覆盖 received_date = pendulum.now().last(pendulum.MONDAY).strftime('%m/%d/%Y %H:%M %p') filter_rule = f"[ReceivedTime] >= '{received_date}' AND [Subject] = 'Automatic Reports'" filtered_messages = messages.Restrict(filter_rule) outputDir = r"C:\Users\xxx\TestEmails" # 确保输出目录存在 if not os.path.exists(outputDir): os.makedirs(outputDir) try: for message in list(filtered_messages): try: sender = message.SenderName for attachment in message.Attachments: save_path = os.path.join(outputDir, attachment.FileName) attachment.SaveAsFile(save_path) print(f"附件 {attachment.FileName} 来自 {sender} 已保存") except Exception as e: print(f"保存附件时出错:{str(e)}") except Exception as e: print(f"处理邮件时出错:{str(e)}")
额外注意事项
如果仍提示无法找到文件夹,检查脚本运行权限与Outlook运行权限是否一致:若Outlook以管理员身份运行,脚本也需要以管理员身份运行,否则会出现COM组件访问权限限制。
内容的提问来源于stack exchange,提问作者Hummer
相关产品推荐
相关产品推荐

