Graph api send mail
To send an email using the Microsoft Graph API, you'll need to use the Microsoft Graph Mail
endpoint. Here's a step-by-step guide to help you get started:
Prerequisites
- Azure AD App Registration: Create an Azure AD application and register it with the necessary permissions. You'll need the
Mail.ReadWrite
andMail.Send
permissions. - Client ID and Client Secret: Note down your client ID and client secret, which you'll use to authenticate with the Microsoft Graph API.
- Tenant ID: Note down your tenant ID, which you'll use to authenticate with the Microsoft Graph API.
Step 1: Authenticate with the Microsoft Graph API
Use the client ID, client secret, and tenant ID to authenticate with the Microsoft Graph API. You can use the client_credentials
flow to authenticate.
Step 2: Send an email using the Microsoft Graph API
Use the Microsoft Graph Mail
endpoint to send an email. The endpoint is https://graph.microsoft.com/v1.0/me/sendMail
.
Request Body
The request body should contain the email details, such as the sender, recipient, subject, and body. Here's an example:
{
"message": {
"subject": "Test email from Microsoft Graph API",
"body": {
"content": "This is a test email sent using the Microsoft Graph API.",
"contentType": "Text"
},
"toRecipients": [
{
"emailAddress": {
"address": "[email protected]"
}
}
],
"from": {
"emailAddress": {
"address": "[email protected]"
}
}
}
}
Headers
You'll need to include the following headers in your request:
Authorization
: Bearer token obtained during authenticationContent-Type
:application/json
Example Request
Here's an example request using curl
:
curl -X POST \
https://graph.microsoft.com/v1.0/me/sendMail \
-H 'Authorization: Bearer <access_token>' \
-H 'Content-Type: application/json' \
-d '{
"message": {
"subject": "Test email from Microsoft Graph API",
"body": {
"content": "This is a test email sent using the Microsoft Graph API.",
"contentType": "Text"
},
"toRecipients": [
{
"emailAddress": {
"address": "[email protected]"
}
}
],
"from": {
"emailAddress": {
"address": "[email protected]"
}
}
}
}'
Response
The response will contain the email ID, which you can use to track the status of the email.
That's it! You've successfully sent an email using the Microsoft Graph API.
Note: Make sure to replace <access_token>
with the actual access token obtained during authentication. Also, ensure that the sender and recipient email addresses are valid and within the same Azure AD tenant.