Warm tip: This article is reproduced from serverfault.com, please click

azure active directory-来自Python的Microsoft Graph API调用

(azure active directory - Microsoft Graph API calls from Python)

发布于 2020-12-10 11:25:09

我的任务很简单。我需要能够从Python在Outlook帐户中创建消息草稿。我了解这需要在Azure Active Directory中注册一个应用程序并设置各自的权限-我已经完成了。我的问题是从Python登录-我不知道该怎么做。我知道有各种方法的示例脚本,但是它们并没有帮助我。我不需要使用Flask创建的任何复杂网页,我只需要登录并进行简单的图形api调用即可。

如果你可以显示一个从Python登录的准系统示例,我将非常感谢。

谢谢!

Questioner
student_123
Viewed
0
Stanley Gong 2020-12-11 16:13:22

如果你正在寻找为某个Azure AD用户创建邮件草稿的简单演示,请尝试以下代码:

import adal
import json
import requests

tenant = '<your tenant name or id>'
app_id = '<your azure ad app id>'
app_password = '<your azure ad app secret>'
userAccount = '<user account you want to create mail draft>'

resource_URL ='https://graph.microsoft.com'
authority_url = 'https://login.microsoftonline.com/%s'%(tenant)

context = adal.AuthenticationContext(authority_url)

token = context.acquire_token_with_client_credentials(
    resource_URL,
    app_id,
    app_password)

request_headers = {'Authorization': 'bearer %s'%(token['accessToken'])}

create_message_URL =resource_URL + '/v1.0/users/%s/messages'%(userAccount)

message_obj = {
    "subject":"Did you see last night's game?",
    "importance":"Low",
    "body":{
        "contentType":"HTML",
        "content":"They were <b>awesome</b>!"
    },
    "toRecipients":[
        {
            "emailAddress":{
                "address":"AdeleV@contoso.onmicrosoft.com"
            }
        }
    ]
}

result = requests.post(create_message_URL, json = message_obj,headers = request_headers)

print(result.text)

结果: 在此处输入图片说明

注意:请确保你的Azure AD应用程序已被授予该应用程序Mail.ReadWrite权限 在此处输入图片说明

如果你还有其他问题,请告诉我。