2

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!

1
  • You can start with this sample which uses Device code flow. Commented Dec 10, 2020 at 11:47

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.