How to use sendMail example code correctly?

Sebastian Eyzaguirre 20 Reputation points
2023-12-07T04:02:01.64+00:00

hey everyone! i'm pretty new to using API's and am getting a bit frustrated with why the sendMail code doesn't work correctly when i install the microsoft sdk package.

Problem is i don't seem to be able to use the SendMailPostRequestBody method. This is what i currently have imported in my python file:

import logging
import requests
import msal
import asyncio
from azure.identity.aio import ClientSecretCredential
from msgraph import GraphServiceClient
import msgraph_core
import msgraph

I'm trying to use the example code seen on the user:sendMail of the Microsoft Graph documentation. Please see below:

# THE PYTHON SDK IS IN PREVIEW. FOR NON-PRODUCTION USE ONLY

graph_client = GraphServiceClient(credentials, scopes)

request_body = SendMailPostRequestBody(
	message = Message(
		subject = "Meet for lunch?",
		body = ItemBody(
			content_type = BodyType.Text,
			content = "The new cafeteria is open.",
		),
		to_recipients = [
			Recipient(
				email_address = EmailAddress(
					address = "******@contoso.onmicrosoft.com",
				),
			),
		],
		cc_recipients = [
			Recipient(
				email_address = EmailAddress(
					address = "******@contoso.onmicrosoft.com",
				),
			),
		],
	),
	save_to_sent_items = False,
)

await graph_client.me.send_mail.post(request_body)

Any helps is greatly appreciated!

Microsoft Security Microsoft Graph
{count} votes

Accepted answer
  1. CarlZhao-MSFT 46,371 Reputation points
    2023-12-07T06:52:46.6233333+00:00

    Hi @Sebastian Eyzaguirre

    If you are using the client credentials flow to request an access token, then you will not be able to call the /me (on behalf of the logged in user) endpoint to send mail, because the client credentials flow runs on the server side, no user interaction. You can only call the /users/{id} endpoint to send mail on behalf of other users.

    await graph_client.users.by_user_id('user-id').send_mail.post(request_body)
    

    Hope this helps.

    If the reply is helpful, please click Accept Answer and kindly upvote it. If you have additional questions about this answer, please click Comment.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.