Search code examples
c#azuremicrosoft-graph-apimicrosoft-graph-sdksmicrosoft-graph-mail

Unable to send an email with the Microsoft Graph SDK


I followed these steps:

  1. I created an app registration in Azure.
  2. Went into Certificates and Secrets and created a new Client Secret.
  3. In API permissions, gave Delegated permission to all Mail.* permission names.
  4. Then I clicked Grant admin consent for {my org}.

In my code (.net core console app), I wrote the following:

var clientId = "23fff856-***";
var tenantId = "6f541345-***";
var clientSecret = "_Sir**(";

IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
    .Create(clientId)
    .WithTenantId(tenantId)
    .WithClientSecret(clientSecret)
    .Build();

var authProvider = new ClientCredentialProvider(confidentialClientApplication);
var graphClient = new GraphServiceClient(authProvider);

var message = new Message
{
    Subject = "my subject",
    Body = new ItemBody {ContentType = BodyType.Text, Content = "body"},
    ToRecipients = new List<Recipient>
    {
        new Recipient
        {
            EmailAddress = new EmailAddress{Address = "[email protected]"}
        }
    }
};

await GraphClient.Me
                .SendMail(message, true)
                .Request()
                .PostAsync();

This results in an error:

"code":"NoPermissionsInAccessToken",
"message":"The token contains no permissions, or permissions can not be understood."

I've given all the permissions. What am I missing?


Solution

  • Since you are using Client credential flow you need to use Application permissions on the Azure portal. Please add Mail.Send Application permission and it will work.

    Remove 'Me' and add Users['Userid'] since 'Me' talks about the logged in user and we don't have any user here.

    Userid is the user object id in Azure AD. You can also use the userPrincipalname for testing. You can get the userid of a user by using /users endpoint and filter with displayname or userPrincipalname.