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

如何用Python访问未开启MFA的O365邮箱?

问题:Python访问未启用MFA的O365邮箱(基于用户名/密码、客户端ID和租户ID)

背景

已成功实现对启用MFA的O365邮箱的访问,但在访问未启用MFA的邮箱时遇到困难:该邮箱无客户端密钥,尝试通过用户名/密码、客户端ID及租户ID认证,查阅msal、O365等库后未找到清晰实现方案。

已实现的MFA邮箱访问代码

from exchangelib import Configuration, OAuth2Credentials, Account, DELEGATE, Build, Version, Identity, OAUTH2

username = ""
directory_id = ""
application_id = ""
client_secret = ""
email_subject = ""

credentials = OAuth2Credentials(client_id=application_id, client_secret=client_secret, tenant_id=directory_id, identity=Identity(primary_smtp_address=username))
version = Version(build=Build(15, 0, 12, 34))
config = Configuration(server='outlook.office365.com', credentials=credentials, version=version, auth_type=OAUTH2)
a = Account(primary_smtp_address=username, config=config, autodiscover=False, access_type=DELEGATE)

filtered_items = a.inbox.filter(subject__contains=email_subject)
count = filtered_items.count()
print(count)

解决方案:使用ROPC OAuth2流程访问无MFA邮箱

针对未启用MFA的账户,可使用OAuth2的**资源所有者密码凭据(ROPC)**流程,无需客户端密钥,仅需用户名、密码、客户端ID和租户ID即可完成认证。以下是基于exchangelib的实现代码:

from exchangelib import Configuration, OAuth2Credentials, Account, DELEGATE, Build, Version, Identity, OAUTH2

# 未启用MFA的邮箱配置信息
username = "your_non_mfa_email@domain.com"
tenant_id = "your_tenant_id"
client_id = "your_application_id"
password = "your_email_password"
email_subject = "target_subject"

# 创建ROPC模式的OAuth2凭据,无需客户端密钥
credentials = OAuth2Credentials(
    client_id=client_id,
    tenant_id=tenant_id,
    identity=Identity(primary_smtp_address=username),
    username=username,
    password=password,
    ropc_mode=True  # 启用ROPC认证模式
)

version = Version(build=Build(15, 0, 12, 34))
config = Configuration(
    server='outlook.office365.com',
    credentials=credentials,
    version=version,
    auth_type=OAUTH2
)

# 初始化邮箱账户
a = Account(
    primary_smtp_address=username,
    config=config,
    autodiscover=False,
    access_type=DELEGATE
)

# 执行与MFA邮箱相同的筛选操作
filtered_items = a.inbox.filter(subject__contains=email_subject)
count = filtered_items.count()
print(count)

关键配置说明

  • Azure AD应用设置:需在Azure门户的应用注册中,进入「身份验证」页面,启用「允许公共客户端流」(ROPC属于公共客户端认证,无需客户端密钥)。
  • 权限配置:确保应用已授予Exchange Online的委托权限(如Mail.Read、Mail.ReadWrite等),并完成管理员同意(若需要)。
  • 限制注意:ROPC流程仅适用于未启用MFA的账户,且因直接处理明文密码,不建议用于生产环境,仅作为临时解决方案使用。

内容的提问来源于stack exchange,提问作者Fun TJ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 14:30:30