Error - "The requested user is invalid" while sendmail using graph api

Viewed 33

I am trying to send mail on behalf of some users using the Microsoft Graph API through my Winforms application. I registered the app in Application Registration at Azure Portal in my tenant and assigned application permissions for sending mail to the app. I am using client credentials flow for sending mail.

The mail is successfully sent when sending the mail on behalf of my tenant user. Then I granted the admin consent to my app from another tenant and tried to send mail on behalf of that tenant's user but I get an error

Code: ErrorInvalidUser
Message: The requested user 'foo@tenanttwo.onmicrosoft.com' is invalid.

That user has a valid license of O365.

Can we send the mail on behalf of other tenant's user using the Microsoft Graph API? If yes then please help me what else I need to do?

This is the code I'm using:

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

// using Azure.Identity;
var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };

// https://docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(tenantID, clientId, clientSecret, options);

var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

var message = new Microsoft.Graph.Message
        {
            Subject = strSubject,
            Body = new ItemBody
            {
                ContentType = BodyType.Text,
                Content = strBody
            },
            ToRecipients = new List<Recipient>()
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = strTo
                }
            }
        }
        };

var saveToSentItems = true;

await graphClient.Users[senderMail]
          .SendMail(message, saveToSentItems)
          .Request()
          .PostAsync();
0 Answers
Related