Hi Suraj
- 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
- 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:
Make sure that your token has the required scopes.
- 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.