通过 python-o365 获取 Outlook 数据

Getting Outlook data via python-o365

好吧,我想从 Outlook 获取日历数据。我的目的是在 Python 中提供小型服务,它可以在 outlook 帐户中读取和写入某人的日历,当然我想我可以在 Azure Active Directory 中访问它。在写这篇文章之前,我阅读了很多关于如何做到这一点的指南。我也试图在 github 上找到类似的问题,我从中学到了一些东西。

所以我做了以下步骤。我希望你指出我的错误并告诉我如何改正它们。

from O365 import Account

CLIENT_ID = 'xxxx'
SECRET_ID = 'xxxx'
TENANT_ID = 'xxxx'

credentials = (CLIENT_ID, SECRET_ID)
account = Account(credentials, auth_flow_type='credentials', tenant_id=TENANT_ID)
if account.authenticate():
    print('Authenticated!')


schedule = account.schedule(resource='user@domain')
calendar = schedule.get_default_calendar()
events = calendar.get_events(include_recurring=False)

for event in events:
    print(event)

然后,如果我使用我目录中用户联系信息中显示的电子邮件作为资源。我收到此错误:

requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://graph.microsoft.com/v1.0/users/user@domain/calendar | Error Message: The tenant for tenant guid 'xxxx' does not exist.

然后如果我使用 'User Principal Name',它作为资源显示在我的目录中的用户身份中。我收到此错误:

requests.exceptions.HTTPError: 403 Client Error: Forbidden for url: https://graph.microsoft.com/v1.0/users/xxxx#EXT%23@xxxx.onmicrosoft.com/calendar | Error Message: Insufficient privileges to complete the operation.

然后如果我使用 'me' 作为资源我也会得到一个错误:

requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/me/calendar | Error Message: /me request is only valid with delegated authentication flow.

你能告诉我我应该提供什么作为资源来获取某人的日历或者我应该修复什么吗?

对我来说,加入 Microsoft Developer Program 并使用其 azure 目录解决了问题。

让我们最好浏览一下错误消息:

  1. Error Message: The tenant for tenant guid 'xxxx' does not exist.

我假设这是一个 Office 365 商业版。此外,您已使用公司地址登录到 Azure。 然后你应该看到:“App registrations > test feature > Overview”你应该找到有效的TenantID。

  1. Error Message: Insufficient privileges to complete the operation.

我在你的示例中找不到范围,例如:

from O365 import Account

CLIENT_ID = 'xxxx'
SECRET_ID = 'xxxx'
TENANT_ID = 'xxxx'

credentials = (CLIENT_ID, SECRET_ID)

scopes = ['https://graph.microsoft.com/Calendar.ReadWrite', 
          'https://graph.microsoft.com/User.Read', 
          'https://graph.microsoft.com/offline_access']

account = Account(credentials, tenant_id=TENANT_ID)
if account.authenticate(scopes=scopes):
   print('Authenticated!') 

你可以check all Scopes here

3。 Error Message: /me request is only valid with delegated authentication flow.

这里我也假设范围错误。

一般建议:

  • 添加“offline_access”作为范围 - 这样您就不需要为每个 运行.
  • 登录
  • 将每个范围设置为委派 - 这会限制用户级别的权限 - 这会降低公司的安全风险。