How to read outlook emails from python

Suraj Sanka 15 Reputation points
2023-07-25T15:10:21.23+00:00
import requests


def get_access_token():
    """Gets an access token for the Microsoft Graph API."""

    url = "https://login.microsoftonline.com/common/oauth2/token"
    data = {
        "grant_type": "client_credentials",
        "client_id": "client_key",
        "client_secret":"client_secret",
        "resource": "https://graph.microsoft.com/"
    }
    response = requests.post(url, data=data)
    if response.status_code == 200:
        return response.json()["access_token"]
    else:
        # print(response.status_code)
        return None


token = get_access_token()
r = requests.get("https://graph.microsoft.com/v1.0/me/messages",
                 headers={"Authorization": "Bearer " + token})

if r.status_code == 200:
    for message in r.json():
        print(message["subject"])
else:
    print("Authentication Failed")


I am using the above code to read emails from Outlook. I am not able to generate any tokens properly to read the emails. I have registered an app in Azure Active Directory and got the client ID and secret.

Please let me know what changes I need to make

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,649 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Azizkhon Ishankhonov 195 Reputation points
    2024-04-25T08:34:24.05+00:00

    Hi Suraj

    1. To read messages from the mail you should give the necessary permissions for your application. Please read the details here: https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0&tabs=python#permissions
    2. There are several options to get tokens with the required scope of permission which allows you to read mail from Outlook (delegated, application), also you may use Python SDK which may help: https://github.com/microsoftgraph/msgraph-sdk-python

    You provide a code for retrieving tokens on behalf of the application(ClientSecretCredential). To successfully run this code you should permit your application on Entra ID, depending on your tenant it might require admin consent and after that, you can easily get a token for your application: enter image description here

    Make sure that your token has the required scopes.

    1. PoC via DeviceCodeCredential
    import asyncio
    from msgraph import GraphServiceClient
    from msgraph.generated.users.item.messages.messages_request_builder import MessagesRequestBuilder
    from azure.identity import AuthorizationCodeCredential, DeviceCodeCredential
    
    credential = DeviceCodeCredential(client_id="your_client_id")
    scopes = ['https://graph.microsoft.com/.default']
    graph_client = GraphServiceClient(credential, scopes)
    
    query_params = MessagesRequestBuilder.MessagesRequestBuilderGetQueryParameters(
    		select = ["sender","subject"],
    )
    
    request_configuration = MessagesRequestBuilder.MessagesRequestBuilderGetRequestConfiguration(
    query_parameters = query_params,
    )
    
    async def get_mail():
        mail = await graph_client.me.messages.get(request_configuration = request_configuration)
        if mail:
            # to do with mail collection
            
    asyncio.run(get_mail())
    

    If it is helpful, please accept the answer.

    0 comments No comments