在Python中无需MFA访问O365邮箱

问题描述 投票:0回答:2

我正在编写一个 Python 脚本来访问我的两个 O365 邮箱。一个邮箱启用了多重身份验证 (MFA),而另一个邮箱则未启用。我已成功实现对启用 MFA 的邮箱的访问。但是,我在使用用户凭据(用户名/密码)以及客户端 ID 和租户 ID 访问邮箱(无需 MFA)时面临挑战。

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)

我想在没有MFA的情况下实现对邮箱的类似访问。 问题是没有 MFA 的邮箱没有客户端密钥。 谢谢!

我搜索了 msal 和 O365 等各种库,但未能找到使用用户名、密码、客户端 ID 和租户 ID 进行非 MFA 身份验证的明确实现。

python-3.x email multi-factor-authentication exchangelib
2个回答
0
投票

O365 不再支持 NTLM 或基本身份验证。您必须使用 OAuth 和客户端密钥进行连接,或者使用基于浏览器的身份验证方法(在其中执行组织的身份验证方法)。文档中有后者的示例:https://ecederstrand.github.io/exchangelib/#msal-on-office-365


0
投票

解决了。 我发现虽然“OAuth2LegacyCredentials”仍然需要“client_secret”,但它可以使用空值。 因此,下面的代码对我有用:

from exchangelib import Configuration, Account, DELEGATE, Build, Version, OAUTH2, OAuth2LegacyCredentials

username = ""
password = ""
directory_id = ""
application_id = ""
email_subject = ""

credentials = OAuth2LegacyCredentials(username=username, password=password, client_id=application_id, tenant_id=directory_id, client_secret="")
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)


© www.soinside.com 2019 - 2024. All rights reserved.