I've been fighting with OAuth and MSAL stuff all day today in python. I have a simple application, users fill my form, click submit and then I write their stuff to a database. I want to send them an email saying "I wrote your stuff to the database" I want that email to come from my system account which is an AZAD account.
I feel like I should be able to somehow get a token to interact with the graph API using ONLY the name, password then send an email. However I keep running into walls.
I can't get ADMIN stuff for my app to just send email as ANY user. All I'm trying to do is send an email from my system account. I CAN do this manually in outlook application on my desktop but I can't do it from my python IDE.
I want to do this using HTTP requests if possible
import requests_oauthlib
from requests_oauthlib import OAuth2Session
from oauthlib.oauth2 import LegacyApplicationClient
tenant_id = tid
client_id = cid
client_secret = cs
uri =f"https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token"
username=un
password=pw
#DOES NOT WORK says the user account doesn't exist
oauth = OAuth2Session(client=LegacyApplicationClient(client_id=client_id))
token = oauth.fetch_token(
token_url=uri
,client_id=client_id
,client_secret=client_secret
,username=username
,password=password
,scope="Mail.Send"
)
#THIS DOES WORK BUT I CANT GET IT TO EMAIL
client = BackendApplicationClient(client_id=client_id)
oauth = OAuth2Session(client=client)
token = oauth.fetch_token(
token_url=uri
,client_id=client_id
,client_secret=client_secret
,scope=["https://graph.microsoft.com/.default"]
)
recipient='[email protected]'
subject="test_subject"
body="test_body"
request_body = {
'message': {
# recipient list
'toRecipients': [
{
'emailAddress': {
'address': recipient
}
}
],
# email subject
'subject': subject,
"body": {
"contentType": "html",
"content": body
},
'importance': 'normal',
}
}
headers = {
'Authorization': 'Bearer ' + token['access_token']
}
GRAPH_ENDPOINT = 'https://graph.microsoft.com/v1.0'
endpoint = GRAPH_ENDPOINT + '/me/sendMail'
response = requests.post(endpoint, headers=headers, json=request_body)
response.raise_for_status() # Raise an exception if request fails
if response.status_code == 202:
print(f"Email sent to: {recipient}")
else:
print(f"Email not sent to: {recipient}")
.onmicrosoft.com
?