Hi ,
Register an application in Azure Active Directory (AD) to obtain the necessary permissions for sending emails via Microsoft Graph API. Make sure to grant the application the required permissions to send emails. Use the client credentials flow or another suitable authentication method to obtain an access token for your Azure AD application.
https://learn.microsoft.com/en-us/azure/active-directory-b2c/microsoft-graph-get-started?tabs=app-reg-ga
Use the access token to make a POST request to the Microsoft Graph API endpoint for sending emails. You can use the /users/{userId}/sendMail endpoint to send emails on behalf of a user. In the request body, specify the recipient email addresses (including external addresses), subject, body, and any other necessary email properties.
Here is python code for this -
import requests
import json
# Azure AD App Registration details
client_id = 'your_client_id'
client_secret = 'your_client_secret'
tenant_id = 'your_tenant_id'
# Microsoft Graph API endpoint
graph_url = 'https://graph.microsoft.com/v1.0'
# Authentication
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
token_data = {
'client_id': client_id,
'client_secret': client_secret,
'scope': 'https://graph.microsoft.com/.default',
'grant_type': 'client_credentials'
}
token_response = requests.post(token_url, data=token_data).json()
access_token = token_response['access_token']
# Email properties
email_properties = {
"message": {
"subject": "Hello World",
"body": {
"contentType": "Text",
"content": "Test Body"
},
"toRecipients": [
{"emailAddress": {"address": "douglas@external.com"}},
{"emailAddress": {"address": "peet@fashion.tv"}}
]
}
}
# Send email via Microsoft Graph API
send_mail_url = f'{graph_url}/users/{sender_email}/sendMail'
headers = {
'Authorization': 'Bearer ' + access_token,
'Content-Type': 'application/json'
}
response = requests.post(send_mail_url, headers=headers, json=email_properties)
if response.status_code == 202:
print("Email sent successfully!")
else:
print("Failed to send email:", response.text)
Mark as solution if it helps.
Thanks,
Sandeep Mishra
@akg1421