Home > database >  Sending mail multiple times by Microsoft Graph
Sending mail multiple times by Microsoft Graph

Time:06-17

Blazor server application

  • I have a web appliction that is using AzureAd and OpenIdConnect to login to this application.

  • I am sending mail by using Microsoft graph and I am using the example in enter image description here

    Why should I use application permission?

    In my case the user logged in for the first time and clicked on the button then the email will be send, but in the second time the application has to communicate with API graph without interaction from the user, that means without user and this exactly what I need(application permission).

    I adjust the code like the following:

    • Client credentials provider:

    The client credential flow enables service applications to run without user interaction. Access is based on the identity of the application. this is from Microsoft doc

          private GraphServiceClient CreateGraphServiceClient()
          {
           // The client credentials flow requires that you request the
           // /.default scope, and preconfigure your permissions on the
           // app registration in Azure. An administrator must grant consent
           // to those permissions beforehand.
           var scopes = new[] { "https://graph.microsoft.com/.default" };
    
           // Multi-tenant apps can use "common",
          // single-tenant apps must use the tenant ID from the Azure portal
          var tenantId = "common";
    
          // Values from app registration
         var clientId = "YOUR_CLIENT_ID";
         var clientSecret = "YOUR_CLIENT_SECRET";
    
         // using Azure.Identity;
         var options = new TokenCredentialOptions
         {
          AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
         };
    
         var clientSecretCredential = new ClientSecretCredential(
         tenantId, clientId, clientSecret, options);
    
       return new GraphServiceClient(clientSecretCredential, scopes);
    }
    
    • Send mail with UserId, you can see the code in Microsoft doc:

      puplic SendMyEmail()
      {
       GraphServiceClient graphClient = CreateGraphServiceClient;
      
       var message = new Message
       {
          Subject = "Meet for lunch?",
          Body = new ItemBody
         {
            ContentType = BodyType.Text,
            Content = "The new cafeteria is open."
         },
        ToRecipients = new List<Recipient>()
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "[email protected]"
                }
            }
        },
        CcRecipients = new List<Recipient>()
        {
            new Recipient
            {
                EmailAddress = new EmailAddress
                {
                    Address = "[email protected]"
                }
            }
         }
       };
      
      var saveToSentItems = false;
      //See GetUserId down
      string userId = await GetUserId();
      
      await graphClient.Users[UserId]
        .SendMail(message,saveToSentItems)
        .Request()
        .PostAsync();
      }
      }
      
    • UserId: To get user Id you need AuthenticationStateProvider, this has to inject in the service of your application and then add to the constructor of your class, then you can use it.

      puplic class MyClass
      {
       private readonly MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler;
        private readonly AuthenticationStateProvider authenticationState;
      
        puplic MyClass(
            MicrosoftIdentityConsentAndConditionalAccessHandler ConsentHandler,
            AuthenticationStateProvider authenticationState)
        {
          this.authenticationState = authenticationState;
          this.ConsentHandler = ConsentHandler;
        }
      
        public async Task<string> GetUserId()
        {
            var authSate = await authenticationState.GetAuthenticationStateAsync();
            return authSate.User.FindFirstValue("http://schemas.microsoft.com/identity/claims/objectidentifier");
        }
       //Here your 
       private GraphServiceClient CreateGraphServiceClient() { ...}
       puplic SendMyEmail() {....}
      }
      
  • Related