Search code examples
pythonazure-active-directorymicrosoft-graph-apimicrosoft-graph-mail

Microsoft Graph API calls from Python


I have a fairly simple task. I need to be able to create draft messages in my Outlook account from Python. I understand this entails registering an app in the Azure Active Directory and setting the respective permissions - that I have done. My problem is in logging in from Python - I cannot figure out how to do it. I know there are sample scripts for various avenues of doing so but they did not help me. I do not need any complicated web pages created with Flask, I just have to login and make a simple graph api call.

If you could show a bare-bones example of logging in from Python I would very much appreciate it.

Thanks!


Solution

  • If you are looking for a simple demo that creating a mail draft for a certain Azure AD user, try the code below:

    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":"[email protected]"
                }
            }
        ]
    }
    
    result = requests.post(create_message_URL, json = message_obj,headers = request_headers)
    
    print(result.text)
    

    Result: enter image description here

    Note: please make sure that your Azure AD application has been granted with the application Mail.ReadWrite permission enter image description here

    Let me know if you have any further questions.