Skip to content

Instantly share code, notes, and snippets.

@ycytai
Created October 29, 2024 02:15
Show Gist options
  • Save ycytai/335e452977858963bdbfca2d5d2cb2a5 to your computer and use it in GitHub Desktop.
Save ycytai/335e452977858963bdbfca2d5d2cb2a5 to your computer and use it in GitHub Desktop.
import msal
import requests
# Replace with your values
CLIENT_ID = 'your-client-id'
CLIENT_SECRET = 'your-client-secret'
TENANT_ID = 'your-tenant-id'
EMAIL = 'sender-email'
# 1. Define the MSAL authentication flow
authority = f"https://login.microsoftonline.com/{TENANT_ID}"
scopes = ["https://graph.microsoft.com/.default"] # Permissions required for Microsoft Graph
# 2. Create a client instance with MSAL
client = msal.ConfidentialClientApplication(
CLIENT_ID,
client_credential=CLIENT_SECRET,
authority=authority,
)
# 3. Acquire a token for Graph API
token_response = client.acquire_token_for_client(scopes)
if 'access_token' in token_response:
access_token = token_response['access_token']
# Set up the email details
email_data = {
"message": {
"subject": "Test Email from Python",
"body": {
"contentType": "Text",
"content": "Hello! This is a test email sent from a Python script using Microsoft Graph API."
},
"toRecipients": [
{
"emailAddress": {
"address": "recipient-email"
}
}
]
},
"saveToSentItems": "true"
}
# 4. Send the email using the Microsoft Graph API
headers = {
"Authorization": f"Bearer {access_token}",
"Content-Type": "application/json"
}
response = requests.post(
f"https://graph.microsoft.com/v1.0/users/{EMAIL}/sendMail",
headers=headers,
json=email_data
)
# Check if the email was sent successfully
if response.status_code == 202:
print("Email sent successfully!")
else:
print(f"Failed to send email. Status code: {response.status_code}")
print(response.json())
else:
print("Failed to acquire access token.")
print(token_response.get("error"))
print(token_response.get("error_description"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment