Skip to content

Instantly share code, notes, and snippets.

@mvelazc0
Created April 12, 2024 15:15
Show Gist options
  • Save mvelazc0/cd03ca73991f52e3cbff0c05ce99eb30 to your computer and use it in GitHub Desktop.
Save mvelazc0/cd03ca73991f52e3cbff0c05ce99eb30 to your computer and use it in GitHub Desktop.
Create an inbox rule on an M365 mailbox using the Microsoft Grapi API
import requests
tenant_id = ''
client_id = ''
client_secret = ''
scope = 'https://graph.microsoft.com/.default'
token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'
token_data = {
'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'scope': scope
}
token_r = requests.post(token_url, data=token_data)
token = token_r.json().get('access_token')
print (token)
user_email = '[email protected]'
graph_endpoint = f'https://graph.microsoft.com/v1.0/users/{user_email}/mailFolders/Inbox/messageRules'
headers = {
'Authorization': f'Bearer {token}',
'Content-Type': 'application/json'
}
data = {
"displayName": "From partner",
"sequence": 2,
"isEnabled": True,
"conditions": {
"senderContains": [
"adele"
]
},
"actions": {
"forwardTo": [
{
"emailAddress": {
"name": "John Doe",
"address": "[email protected]"
}
}
],
"stopProcessingRules": True
}
}
response = requests.post(graph_endpoint, headers=headers, json=data)
if response.status_code == 201:
print ('Created!')
else:
print(f'Error: {response.status_code}')
print (response.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment