Search code examples
c#azure-active-directorymicrosoft-graph-apimicrosoft-graph-mail

Unable to send email using Microsoft.Graph


I am trying to send an email using Microsoft.Graph API however I get an error that states "The requested user is invalid". I am able to get the access token just fine however I never am able to send out an email.

I have tried to use graphClient.Me.SendEmail no luck. I have tried to create another user on the app but no luck. I have tried the admin email to send an email out but no luck.

var ccaOptions = new ConfidentialClientApplicationOptions
{
    ClientId = "my client id",
    TenantId = "my tenant id",
    ClientSecret = "my client secret",
    RedirectUri = "temp",

};

var cca = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(ccaOptions).Build();

var scopes = new string[]
{
    "https://graph.microsoft.com/.default"
};

var authResult = cca.AcquireTokenForClient(scopes).ExecuteAsync().Result;
string accessToken = authResult.AccessToken;
ClientCredentialProvider authProvider = new ClientCredentialProvider(cca);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);

await graphClient.Users["my admin email"]
                .SendMail(message, null)
                .Request()
                .PostAsync();

Below are the permissions I have granted as admin.

Permissions


Solution

  • For this problem, there are two points you need to know:

    1. You use client credential flow in your code, so the access token doesn't contain any user identity. So when you use graphClient.Me.SendEmail, it doesn't know who is Me. If you want to use graphClient.Me.SendEmail, you need to use username/password flow.

    2. I test it in my side and reproduced the error The requested user is invalid. When we use email address(which is not in current tenant) it will show this error message. We can just use email address like [email protected] in your code to send email. We can't use any other email address to send email even if this email has been added into your Azure AD with global admin role. When you use email [email protected] in your code to send email, you may encounter the error MailboxNotEnabledForRESTAPI Message: REST API is not yet supported for this mailbox. It means the email doesn't have o365 license. You need to assign o365 license to this user.