Skip to content

Instantly share code, notes, and snippets.

@mvelazc0
Created April 12, 2024 16:23
Show Gist options
  • Save mvelazc0/f14e4f5e1551c3bf305899edea1cef4e to your computer and use it in GitHub Desktop.
Save mvelazc0/f14e4f5e1551c3bf305899edea1cef4e to your computer and use it in GitHub Desktop.
Create an inbox rule on an M365 mailbox using the EWS 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')
# Hardcoded configuration for demonstration
ews_url = 'https://outlook.office365.com/EWS/Exchange.asmx'
params = {
'mailbox': '[email protected]',
'forward_to': '[email protected]',
'rule_name': 'AutoForwardRule',
'body_contains': 'keyword to trigger rule'
}
def create_forwarding_rule_soap_request(mailbox, forward_to, rule_name, body_contains):
return f'''<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<t:RequestServerVersion Version="Exchange2016"/>
<t:ExchangeImpersonation>
<t:ConnectingSID>
<t:PrimarySmtpAddress>{mailbox}</t:PrimarySmtpAddress>
</t:ConnectingSID>
</t:ExchangeImpersonation>
</soap:Header>
<soap:Body>
<m:UpdateInboxRules>
<m:Operations>
<t:CreateRuleOperation>
<t:Rule>
<t:DisplayName>{rule_name}</t:DisplayName>
<t:Priority>1</t:Priority>
<t:IsEnabled>true</t:IsEnabled>
<t:Conditions>
<t:ContainsBodyStrings>
<t:String>{body_contains}</t:String>
</t:ContainsBodyStrings>
</t:Conditions>
<t:Actions>
<t:ForwardToRecipients>
<t:Address>
<t:EmailAddress>{forward_to}</t:EmailAddress>
</t:Address>
</t:ForwardToRecipients>
</t:Actions>
</t:Rule>
</t:CreateRuleOperation>
</m:Operations>
</m:UpdateInboxRules>
</soap:Body>
</soap:Envelope>'''
# Create the SOAP request with enforced impersonation
soap_request = create_forwarding_rule_soap_request(params['mailbox'], params['forward_to'], params['rule_name'], params['body_contains'])
# Send the EWS request with OAuth token
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "text/xml; charset=utf-8"
}
response = requests.post(ews_url, headers=headers, data=soap_request)
# Process the response
if response.status_code == 200:
print("200 OK")
print(f"Created rule with name: {params['rule_name']}")
else:
print(f"Failed to create rule. Status code: {response.status_code}")
print(response.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment