-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsmtp_mail.py
48 lines (38 loc) · 1.38 KB
/
smtp_mail.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import msal
import requests
# Azure application details
# OAuth2 authority and scopes
authority = f"https://login.microsoftonline.com/{tenant_id}"
scopes = ["https://graph.microsoft.com/.default"]
# Acquire access token
app = msal.ConfidentialClientApplication(
client_id, authority=authority, client_credential=client_secret
)
token_response = app.acquire_token_for_client(scopes=scopes)
if "access_token" in token_response:
print("Access token acquired successfully.")
# Send email using Microsoft Graph API
headers = {
"Authorization": f"Bearer {token_response['access_token']}",
"Content-Type": "application/json"
}
email_data = {
"message": {
"subject": "Hello from Python!",
"body": {"contentType": "Text", "content": "This is a test email sent using Microsoft Graph API."},
"toRecipients": [
{"emailAddress": {"address": "[email protected]"}}
]
}
}
response = requests.post(
"https://graph.microsoft.com/v1.0/users/[email protected]/sendMail",
headers=headers,
json=email_data
)
if response.status_code == 202:
print("Email sent successfully!")
else:
print(f"Failed to send email: {response.status_code}, {response.text}")
else:
print("Failed to acquire access token:", token_response.get("error_description"))