python - 来自 Python 的 Microsoft Graph API 调用

标签 python azure-active-directory microsoft-graph-api microsoft-graph-mail

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

如果您能展示一个从 Python 登录的简单示例,我将非常感激。

谢谢!

最佳答案

如果您正在寻找为特定 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":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f2e0b0a030a392f0c00011b001c0041000102060c1d001c00091b410c0002" rel="noreferrer noopener nofollow">[email protected]</a>"
            }
        }
    ]
}

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

print(result.text)

结果: enter image description here

注意:请确保您的 Azure AD 应用程序已被授予应用程序 Mail.ReadWrite 权限 enter image description here

如果您还有任何其他问题,请告诉我。

关于python - 来自 Python 的 Microsoft Graph API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65233590/

相关文章:

python - py2exe MemoryLoadLibrary 加载 _ssl.pyd 失败,Win7<->Win10

python - 如何为一个 Python/C 扩展源文件指定不同的编译器标志?

azure - 运行删除-AzureRMAdGroup 所需的权限

Azure AD B2C - 从所有 session 中注销用户

office365api - 使用 Microsoft Graph API 获取所有用户数据

python - 微软图形API : Limiting MSAL Python Daemon app to individual user access

firebase - "The provided value for the input parameter ' redirect_uri ' is not valid"使用 firebase

python - 没有 QtGui 和 QtWidgets 的 PyQt5

python - 使用 openpyxl 访问具有特定范围的命名范围

git - VSTS - 连接到 Azure Active Directory 后无法进行 git push