Outlook特定发件人附件下载Python脚本Credentials导入报错求助
解决exchangelib中Credentials导入错误的问题
错误原因
出现ImportError: cannot import name 'Credentials' from partially initialized module 'exchangelib'的核心原因:
- 导入路径过时:exchangelib版本更新后,
Credentials的导入位置从exchangelib.util迁移到了主模块exchangelib下 - 文件命名冲突:若你的脚本文件名为
exchangelib.py,会和库本身重名,触发循环导入问题
解决步骤
- 修正导入语句
将原有两行导入代码:
from exchangelib import Account, DELEGATE from exchangelib.util import Credentials
替换为:
from exchangelib import Account, DELEGATE, Credentials
- 升级exchangelib版本
如果修正导入后仍报错,检查并升级到最新稳定版:
pip install --upgrade exchangelib
- 排查文件命名冲突
确保你的脚本文件名不是exchangelib.py,避免覆盖库模块导致导入失败。
修正后的完整代码
from exchangelib import Account, DELEGATE, Credentials def download_attachments(username, password, sender_email, save_path): credentials = Credentials(username, password) account = Account(username, credentials=credentials, autodiscover=True, access_type=DELEGATE) for item in account.inbox.filter(sender__icontains=sender_email).order_by('-datetime_received')[:5]: print(f"Subject: {item.subject}") print(f"From: {item.sender.email_address}") print(f"Received: {item.datetime_received}") if item.attachments: for attachment in item.attachments: save_file_path = f"{save_path}/{attachment.name}" with open(save_file_path, "wb") as f: f.write(attachment.content) print(f"Attachment '{attachment.name}' downloaded to {save_file_path}") if __name__ == "__main__": username = "*****@outlook.com" password = "your_password" sender_email = "******@outlook.com" save_path = input("Enter the path to save attachments (default is current directory): ") or "." download_attachments(username, password, sender_email, save_path)
内容的提问来源于stack exchange,提问作者vineesha shyamala
相关产品推荐
相关产品推荐

