30DaysMSGraph – Day 18 – Use Case: Update User Mailbox Settings

Srinivas Varukala

List of all posts in the #30DaysMSGraph series

In Day 17 we extended the base .Net Core console application to assign license to a user in Azure AD. Today we’ll extend the base console application to update the users (exchange online) mailbox settings in Office 365.  Note that it is not required to perform each of the daily Use Case samples in order to continue to the next.  Starting with the base console application from Day 15 will be sufficient if building from scratch, or as always, you can clone the completed version in the provided repo at bottom of this post. The application uses a client secret and the Microsoft Authentication Library (MSAL) to establish an authentication context with the Microsoft Graph API.

Today we will explore the process of updating a user mailbox in preparation for onboarding a user.

Retrieve and Update User Mailbox Settings

In preparation for onboarding a user, once the user is created and appropriate license is applied, now we can update the user specific mailbox settings like the users time zone, locale info, working hours etc.

You can use the Microsoft Graph endpoint /users/{id|userPrincipalName}/mailboxSettings to access a users mailbox settings. You can find the Microsoft Graph documentation to retrieve mailbox settings here and the documentation to update mailbox settings here.

To read and update users mailbox settings it requires new permissions. As such the Azure AD App Registration needs to be updated to include the following application permissions: User.Read.All, MailboxSettings.Read, MailboxSettings.ReadWrite.

This is optional: in addition to the above lets add Mail.Read application permission too as the code sample showcases how to use Microsoft Graph SDK to retrieve users inbox messages too.

With the necessary permissions configured it is time to look at new the code required.

Get and Set User Mailbox Default Time zone

Below you will see the two helper methods that will get and set the user mailbox default time zone.

public async Task<string> GetUserMailboxDefaultTimeZone(string alias)
{
    User user = FindByAlias(alias).Result;
    User detailedUser = await _graphClient.Users[user.Id].Request().Select("MailboxSettings").GetAsync();
    return detailedUser.MailboxSettings.TimeZone;
}
The above method uses Microsoft Graph SDK to retrieve the supplied users current time zone setting.
public async void SetUserMailboxDefaultTimeZone(string alias, string timezone)
{
   User user = FindByAlias(alias).Result;
   Uri Uri = new Uri("https://graph.microsoft.com/v1.0/users/"+ user.Id +"/mailboxSettings");
   String jsonContent = "{\"timeZone\" : \""+ timezone +"\"}";
   HttpContent httpContent = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
   await _httpClient.PatchAsync(Uri, httpContent);
}
Above method takes the user alias and the timezone value that must be applied to the users mailbox.
Note: An important thing to note here is that this method uses HttpClient instead of using Microsoft Graph SDK to update the mailbox settings. The reason for this is because as of today (Nov 18th 2018) there is no support to update MailboxSettings using the SDK. This capability is under work and it will be available soon.
Now that the helper methods are ready. You can call into these methods from the Program.cs class using below method:
private static void GetUserMailboxDefaultTimeZone()
{
   const string alias = "admin";
   var mailboxHelper = new MailboxHelper(_graphServiceClient);
   var defaultTimeZone = mailboxHelper.GetUserMailboxDefaultTimeZone(alias).Result;
   Console.WriteLine("Default timezone: "+ defaultTimeZone);
}

private static void SetUserMailboxDefaultTimeZone()
{
   const string alias = "admin";
   var mailboxHelper = new MailboxHelper(_graphServiceClient, _httpClient);
   mailboxHelper.SetUserMailboxDefaultTimeZone(alias, "Eastern Standard Time");
}
Note the SetUserMailboxefaultTimeZone method is initiating the MailboxHelper with both the _graphServiceClient and _httpClient. The reason for this is because the SetUserMailboxDefaultTimeZone in the MailboxHelper.cs is using both the client objects. The GraphServiceClient object is used to find the user using the alias. The HttpClient object is used to update the mailboxsettings.

Create and Retrieve User Mailbox Message Rules

The MailboxHelper class has additional methods that will showcase how to use Microsoft Graph SDK to retrieve user messages, create and retrieve message rules. Below is code snippet that encapsulates creation and retrieving of mailbox message rules.
private static MessageRule BuildMailRule(string displayName, int sequence, bool isEnabled, string senderContains, string forwardToEmail)
{
    IEnumerable<string> senderContainsList = new string[]{senderContains};
    EmailAddress email = new EmailAddress(){
                Address = forwardToEmail
            };
    Recipient recipient = new Recipient(){
                EmailAddress = email
            };
    IEnumerable<Recipient> recipientList = new Recipient[]{ recipient };
    var msgRule = new MessageRule{
                DisplayName = displayName,
                Sequence = sequence,
                IsEnabled = isEnabled,
                Conditions = new MessageRulePredicates{
                    SenderContains = senderContainsList
                },
                Actions = new MessageRuleActions{
                    ForwardTo = recipientList
                }
            };
            return msgRule;
}
Above is the helper method that takes various parameters needed to create a new message rule.
public async Task CreateRule(string alias, string displayName, int sequence, bool isEnabled, string senderContains, string forwardToEmail)
{
    MessageRule rule = BuildMailRule(displayName, sequence, isEnabled, senderContains, forwardToEmail);
    User user = FindByAlias(alias).Result;
    await _graphClient.Users[user.Id].MailFolders.Inbox.MessageRules.Request().AddAsync(rule);
}
Above method users the BuildMailRule helper method to create a new MessageRule object and then uses Microsoft Graph SDK to add the rule to the users mailbox.
public async Task<List<ResultsItem>> GetUserMailboxRules(string alias)
{
    User user = FindByAlias(alias).Result;
    IMailFolderMessageRulesCollectionPage rules = await _graphClient.Users[user.Id].MailFolders.Inbox.MessageRules.Request().GetAsync();
    List<ResultsItem> items = new List<ResultsItem>();
    if (rules?.Count > 0)
    {
    	foreach (MessageRule rule in rules)
        {
           items.Add(new ResultsItem{
                        Display = rule.DisplayName,
                        Id = rule.Id
                    });
        }
    }
    return items;
}
Above method uses Microsoft Graph SDK to retrieve the message rules and then populates a List object with the rules collection.
There are additional details and functionality that you can find in the code sample provided in the repository. The complete set of instructions and code are on GitHub in the dotnetcore-console-sample repo for you try it yourself.

Try It Out

Navigate to the dotnetcore-console-sample repo.  Do one (or both) of the following:

Day 18 repo link

  1. Clone the repo and configure the project in the Day 18 subfolder.
  2. Follow the instructions in Day 18 to build the project from scratch yourself.

If you run into any issues while building or configuring the project please create a new Issue on the repo.

Join us tomorrow as we continue the onboarding steps for the user within an Office 365 tenant using Microsoft Graph requests in Day 19.

Feedback usabilla icon