Skip to main content

Finding the TimeZone being used in a Mailbox using EWS

If you ever have the need to create a number of events in user mailbox's from a central application or Script where the target Mailboxes span across different time zones then finding each target Mailbox's timezone is a critical thing. In this post I'm going to outline a few different methods of getting the TimeZone using EWS.

If you have access to the Exchange Management Shell cmdlet's to find the users configured timezone you can use either the Get-MailboxCalendarConfiguration or Get-MailboxRegionalConfiguration cmdlets which show you the timezone settings of a Mailbox from the WorkHours configuration of that mailbox. The object in the Mailbox that the information is read from/stored in is the IPM.Configuration.WorkHours FAI (Folder Assoicated Items) object in the Calendar Folder of the Mailbox. So if you want to access the TimeZone setting in Mailbox just using EWS you need to Bind to this UserConfiguration object (FAI object) and then parse the TimeZone Settings out of the WorkHours configuration XML document(which is documented in https://msdn.microsoft.com/en-us/library/ee157798(v=exchg.80).aspx) eg in Powershell something like the following should work okay

function GetWorkHoursTimeZone
{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the Calendar Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
   $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.WorkHours") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($Calendar.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "WorkHours", $Calendar.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    [XML]$WorkHoursXMLString = [System.Text.Encoding]::UTF8.GetString($UsrConfig.XmlData) 
    $returnVal = $WorkHoursXMLString.Root.WorkHoursVersion1.TimeZone.Name
    write-host ("Parsed TimeZone : " + $returnVal)
    Write-Output $returnVal
   }
   else
   {
    write-host ("No Workhours Object in Mailbox")
    Write-Output $null
   }
 }
}

 The other place in an Exchange Malbox where TimeZone information is held is in the OWA Configuration. This is set when a user logs onto to OWA the first time and then selects the timezone, the configuration is then stored in another FAI (in a Roaming Dictionary)with an ItemClass of IPM.Configuration.OWA.UserOptions in the NON_IPM root of the mailbox. Eg the following can be used to access this setting using EWS

function GetOWATimeZone{
    param( 
     [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
   # Bind to the RootFolder Folder
   $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Root,$MailboxName)   
   $RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
   $sfFolderSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Configuration.OWA.UserOptions") 
   #Define ItemView to retrive just 1000 Items    
   $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1) 
   $ivItemView.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
   $fiItems = $service.FindItems($RootFolder.Id,$sfFolderSearchFilter,$ivItemView) 
   if($fiItems.Items.Count -eq 1)
   {
    $UsrConfig = [Microsoft.Exchange.WebServices.Data.UserConfiguration]::Bind($service, "OWA.UserOptions", $RootFolder.Id, [Microsoft.Exchange.WebServices.Data.UserConfigurationProperties]::All)  
    if($UsrConfig.Dictionary.ContainsKey("timezone"))
    {
     $returnVal = $UsrConfig.Dictionary["timezone"]
     write-host ("OWA TimeZone : " + $returnVal)
     Write-Output $returnVal
    }
    else
    {
     write-host ("TimeZone not set")
     Write-Output $null
    }
    
    
   }
   else
   {
    write-host ("No Workhours OWAConfig for Mailbox")
    Write-Output $null
   }
 }
}

If you tried both of these locations and still can't find the TimeZone (or your get a conflicting result) the last method you could try is to enumerate the last X number of appointments that where created by the user in the calendar (either a meeting they organized or a non meeting) and then enumerate the timezone used on those objects. The following is a sample of using the Calendar Appointments to work out the timezone of the user (It should return the most commonly used timezone base on the last 150 Calendar items).

function GetTimeZoneFromCalendarEvents{
    param( 
  [Parameter(Position=0, Mandatory=$true)] [String]$MailboxName,
  [Parameter(Position=1, Mandatory=$true)] [Microsoft.Exchange.WebServices.Data.ExchangeService]$service
    )
 Begin
 {
  $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Calendar,$MailboxName)   
  $Calendar = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
  $tzList = [TimeZoneInfo]::GetSystemTimeZones()
  $AppointmentStateFlags = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8217,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ResponseStatus = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Appointment,0x8218,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer);  
  $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(150)  
  $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
  $psPropset.Add($AppointmentStateFlags)
  $psPropset.Add($ResponseStatus)
  $ivItemView.PropertySet = $psPropset
  $fiItems = $service.FindItems($Calendar.Id,$ivItemView)
  $tzCount = @{}
  if($fiItems.Items.Count -gt 0){
   foreach($Item in $fiItems.Items){
    $AppointmentStateFlagsVal = $null
    [Void]$Item.TryGetProperty($AppointmentStateFlags,[ref]$AppointmentStateFlagsVal)
    $ResponseStatusVal = $null
    [Void]$Item.TryGetProperty($ResponseStatus,[ref]$ResponseStatusVal)
    if($ResponseStatusVal -eq "Organizer" -bor $AppointmentStateFlagsVal -eq 0)
    {
     if($tzCount.ContainsKey($Item.TimeZone))
     {
      $tzCount[$Item.TimeZone]++
     }
     else
     {
      $tzCount.Add($Item.TimeZone,1)
     }
    }
   }    
  }
  $returnVal = $null
  if($tzCount.Count -gt 0){
   $fav = ""
   $tzCount.GetEnumerator() | sort -Property Value -Descending | foreach-object {
      if($fav -eq "")
      {
         $fav = $_.Key
      }
   }
    foreach($tz in $tzList)
   {
    if($tz.DisplayName -eq $fav)
    {
     $returnVal = $tz.Id
    }
   }
  }
  Write-Host ("TimeZone From Calendar Appointments : " + $returnVal)
  Write-Output $returnVal
 }
}

I've included all of these functions in a module that I've posted on GitHub here

Popular posts from this blog

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Gr...

EWS-FAI Module for browsing and updating Exchange Folder Associated Items from PowerShell

Folder Associated Items are hidden Items in Exchange Mailbox folders that are commonly used to hold configuration settings for various Mailbox Clients and services that use Mailboxes. Some common examples of FAI's are Categories,OWA Signatures and WorkHours there is some more detailed documentation in the https://msdn.microsoft.com/en-us/library/cc463899(v=exchg.80).aspx protocol document. In EWS these configuration items can be accessed via the UserConfiguration operation https://msdn.microsoft.com/en-us/library/office/dd899439(v=exchg.150).aspx which will give you access to either the RoamingDictionary, XMLStream or BinaryStream data properties that holds the configuration depending on what type of FAI data is being stored. I've written a number of scripts over the years that target particular FAI's (eg this one that reads the workhours  http://gsexdev.blogspot.com.au/2015/11/finding-timezone-being-used-in-mailbox.html is a good example ) but I didn't have a gene...

Sending a MimeMessage via the Microsoft Graph using the Graph SDK, MimeKit and MSAL

One of the new features added to the Microsoft Graph recently was the ability to create and send Mime Messages (you have been able to get Message as Mime for a while). This is useful in a number of different scenarios especially when trying to create a Message with inline Images which has historically been hard to do with both the Graph and EWS (if you don't use MIME). It also opens up using SMIME for encryption and a more easy migration path for sending using SMTP in some apps. MimeKit is a great open source library for parsing and creating MIME messages so it offers a really easy solution for tackling this issue. The current documentation on Send message via MIME lacks any real sample so I've put together a quick console app that use MSAL, MIME kit and the Graph SDK to send a Message via MIME. As the current Graph SDK also doesn't support sending via MIME either there is a workaround for this in the future my guess is this will be supported.
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.