You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Outlook特定发件人附件下载Python脚本Credentials导入报错求助

解决exchangelib中Credentials导入错误的问题

错误原因

出现ImportError: cannot import name 'Credentials' from partially initialized module 'exchangelib'的核心原因:

  • 导入路径过时:exchangelib版本更新后,Credentials的导入位置从exchangelib.util迁移到了主模块exchangelib下
  • 文件命名冲突:若你的脚本文件名为exchangelib.py,会和库本身重名,触发循环导入问题

解决步骤

  1. 修正导入语句
    将原有两行导入代码:
from exchangelib import Account, DELEGATE 
from exchangelib.util import Credentials

替换为:

from exchangelib import Account, DELEGATE, Credentials
  1. 升级exchangelib版本
    如果修正导入后仍报错,检查并升级到最新稳定版:
pip install --upgrade exchangelib
  1. 排查文件命名冲突
    确保你的脚本文件名不是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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 15:52:35