Hello Jonathan G,
If you are using delegated flows like device code flow, user need to login every time and you must add Delegated
type permissions with admin consent.
But if the use case is with daemon setup where user login must be avoided, you need to switch to client credentials flow by granting Application
type permissions with admin consent.
Initially, I registered one application and granted Mail.Send
permission of Application type with admin consent as below:
Now, I used below sample Microsoft Graph Python SDK code to send mail using client credentials flow:
import asyncio
from azure.identity import ClientSecretCredential
from msgraph.graph_service_client import GraphServiceClient
from msgraph.generated.models.message import Message
from msgraph.generated.models.item_body import ItemBody
from msgraph.generated.models.body_type import BodyType
from msgraph.generated.models.recipient import Recipient
from msgraph.generated.models.email_address import EmailAddress
from msgraph.generated.users.item.send_mail.send_mail_post_request_body import SendMailPostRequestBody
TENANT_ID = "tenantId"
CLIENT_ID = "appId"
CLIENT_SECRET = "secret"
SENDER = "******@xxxxxxxx.onmicrosoft.com"
RECIPIENT = "******@xxxxxxx.onmicrosoft.com"
async def send_mail():
credential = ClientSecretCredential(
tenant_id=TENANT_ID,
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET
)
client = GraphServiceClient(credential, ["https://graph.microsoft.com/.default"])
message = Message(
subject="Graph SDK Mail Test",
body=ItemBody(
content_type=BodyType.Text,
content="This is a test email sent using the Graph SDK"
),
to_recipients=[
Recipient(
email_address=EmailAddress(
address=RECIPIENT
)
)
]
)
mail_body = SendMailPostRequestBody(
message=message,
save_to_sent_items=True
)
await client.users.by_user_id(SENDER).send_mail.post(body=mail_body)
print("Email sent successfully.")
if __name__ == "__main__":
asyncio.run(send_mail())
Response:
To confirm that, I checked Sent Items
of sender user where mail sent successfully as below:
Let me know if you have further queries on this. I'll be happy to assist.
Hope this helps!
If this answers your query, do click Accept Answer
and Yes
for was this answer helpful, which may help members with similar questions.
If you have any other questions or are still experiencing issues, feel free to ask in the "comments" section, and I'd be happy to help.