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

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia  https://en.wikipedia.org/wiki/Opportunistic_TLS .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th

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 Graph is limited to a m
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.