I'm working on python code to send an email from Outlook using Microsoft Graph API. For this, I have created an Enterprise Application in my Azure Active Directory Tenant. I have granted admin consent for the tenant to the application on Mail.Send permission. I'm able to get the access token for Graph API with the help of this application, but I'm not able to send the mail. Can anyone please help me to understand, what is the issue with my code.

Python Code:

from requests import post


LOGIN_URI = f'https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token'

headers = {
    'Host': 'login.microsoftonline.com',
    'Content-Type': 'application/x-www-form-urlencoded'

body = {
    'client_id': CLIENT_ID,
    'scope': 'https://graph.microsoft.com/.default',
    'client_secret': CLIENT_SECRET_VALUE,
    'grant_type': 'client_credentials',
    'tenant': TENANT_ID

response = post(url=LOGIN_URI, headers=headers, data=body)
response_body = response.json()

authorization_token = f"{response_body['token_type']} {response_body['access_token']}"


email_header = {
    'Authorization': authorization_token,
    'Content-Type': 'application/json'

message = {
    'body': {
        'content': 'Outlook Mail Testing Demo',
        'contentType': 'Text'
    'sender': {
        'emailAddress': {
            'address': 'email.address.of.shared.mailbox@active-directory-tenant.tld',
            'name': 'Name of Shared Mailbox'
    'subject': 'Testing email',
    'toRecipients': [
            'emailAddress': {
                'address': 'temprorary.email.address@another-domain.tld',
                'name': 'Name of person to whom email belongs'

email_body = {
    'message': message

email_send_response = post(url='https://graph.microsoft.com/v1.0/users/me/sendMail', headers=email_header, data=email_body)

[N.B.: On running the code, I'm getting error:

400 Client Error: Bad Request for url: https://graph.microsoft.com/v1.0/users/me/sendMail



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.