How can I create group mail alias using office 365

2019-09-21 16:15发布

问题:

How can I create aliases for groups or specific e-mail accounts using the Office 365 API using C#?

I want to dynamically create a group alias name for a group (or specific email) that was already created in Office 365.

回答1:

In this case, you can consider using the Microsoft Graph - Create Group

First, ensure you have assigned the "Microsoft Graph" > "Read and write all groups" permission to app in Azure AD.

Code for your reference:

        string authority = "https://login.windows.net/yourdomain.onmicrosoft.com";

        string clientId = "{client_id}";

        Uri redirectUri = new Uri("http://localhost");

        string resourceUrl = "https://graph.microsoft.com";

        HttpClient client = new HttpClient();

        AuthenticationContext authenticationContext = new AuthenticationContext(authority, false);

        AuthenticationResult authenticationResult = authenticationContext.AcquireToken(resourceUrl,
            clientId, redirectUri, PromptBehavior.Always);

        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + authenticationResult.AccessToken);

        string content = @"{
          'displayName': 'mailgrouptest',
          'groupTypes': ['Unified'],
          'mailEnabled': true,
          'mailNickname': 'mailalias1',
          'securityEnabled': false
        }";

        var httpContent = new StringContent(content, Encoding.GetEncoding("utf-8"), "application/json");

        var response = client.PostAsync("https://graph.microsoft.com/v1.0/groups", httpContent).Result;

        Console.WriteLine(response.Content.ReadAsStringAsync().Result);