Using Microsoft graph api to send mail from powershell

Thangavel Daniel Tamilarasan 271 Reputation points
2021-11-15T15:34:34.45+00:00

Hi,

I have registered Managed identity app with following api permissions,

149453-apiper.png

then I was trying to generate the token as the follows, from the on-premise in powerhsell.

$tokenBody = @{
Grant_Type = "client_credentials"
Scope = "https://graph.microsoft.com/.default"
Client_Id = 'xxxx' // client ID
Client_Secret = 'xxxx' // cleint seceret
}

$tokenResponse = Invoke-RestMethod -Uri "https://login.microsoftonline.com/xxxxxxxxxx(tenantid)/oauth2/v2.0/token" -Method POST -Body $tokenBody

Token is successfully generated, then I try the following to send email,

$headers = @{
"Authorization" = "Bearer $($tokenResponse.access_token)"
"Content-type" = "application/json"
}
$MailSender = "xxxxxxxxxx@xxxxxx .com"

$URLsend = "https://graph.microsoft.com/v1.0/users/$MailSender/sendMail"  

$jsonrequest=@'
{
"subject":"Did you see last night's game?",
"importance":"Low",
"body":{
"contentType":"HTML",
"content":"They were <b>awesome</b>!"
},
"toRecipients":[
{
"emailAddress":{
"address":"yyyyyyyyyyyyyy@永爱不变 .com"
}
}
]
}
'@

$Response = Invoke-RestMethod -Uri $URLsend -Headers $headers -Body $jsonrequest -Method Post

But the above http post failed with authentication error. Please help if I am missing something.

I also tried the api for createderaft - no help. its the same error.

149400-image.png

Microsoft Security | Microsoft Entra | Microsoft Entra ID
Microsoft Security | Microsoft Graph
{count} votes

1 answer

Sort by: Most helpful
  1. Glen Scales 4,446 Reputation points
    2021-11-15T23:31:08.913+00:00

    Your trying to use the Client Credentials flow

    Grant_Type = "client_credentials"

    But in your screen shot your using Delegate permissions, for this flow you must use Application permissions (and have them consented to) eg

    149508-image.png

    0 comments No comments

Your answer

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