Facing issue Send Email though MS Graph Delegated permission

Akhil Tyagi (Tata Consultancy Services) 0 Reputation points Microsoft Vendor
2024-02-09T21:23:56.9733333+00:00

I want to send email from service account through delegated permission, I tried two approaches but getting error while sending email: Approach 1:

Approach IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
        .Create("ClientId")
        .WithTenantId("TenantId")
        .Build();
  UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication);
  GraphServiceClient _graphClient = new GraphServiceClient(authProvider);
await _graphClient.Me
      .SendMail(message, true)
       .Request().WithUsernamePassword("ServiceAccountUser", "ServiceAccountUserPassword")
      .PostAsync().ConfigureAwait(false);

Error: The given key 'Microsoft.Graph.AuthenticationHandlerOption' was not present in the dictionary. Approach 2:

 string[] scopes = { "Mail.Send" };
  var options = new UsernamePasswordCredentialOptions
 {
     AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
 };
 var userNamePasswordCredential = new UsernamePasswordCredential(
            "ServiceAccountUser", "ServiceAccountUserPassword", tenantId, clientId, options);
 var graphClient = new GraphServiceClient(userNamePasswordCredential, scopes);
 await graphClient.Me
         .SendMail(message, true)
          .Request()
         .PostAsync().ConfigureAwait(false);


Error: Code: generalException
Message: An error occurred sending the request.
UsernamePasswordCredential authentication failed: AADSTS65001: The user or administrator has not consented to use the application with ID 'DumyId' named 'DumyName'. Send an interactive authorization request for this user and resource.
Added Permission:User's image Query: I want to send an email from my Azure Web application from Service Account through MS Graph, can you please help me to move forward ?

Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
10,010 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,978 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Akash Jadav 80 Reputation points Microsoft Vendor
    2024-02-10T07:59:33.8833333+00:00

    Hello Akhil, Admin consent needs to be provided or you will need to have one pop-up authentication windows authenticating user. Please refer following reference:
    https://learn.microsoft.com/en-us/graph/permissions-overview?tabs=http

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