Skip to main content

A look into Conversations with EWS and Powershell in a Mailbox

Conversation views in email clients have become par for the course these days, while I'm personally not a great fan it can be a useful feature to use when looking at Mailbox data. With EWS from Exchange 2010 you can use the dedicated EWS operations which are documented http://msdn.microsoft.com/en-us/library/office/dn610351(v=exchg.150).aspx . In Exchange 2013 the conversation operations have been enhanced to offer more functionality such as the ability to use an AQS QueryString to filter the results plus also the ability to apply actions to conversation like applying categories or a specific retention tag.

One interesting thing you can apply these conversation operations to is looking at Mailbox statistics in a different way by looking at the operation of Mailboxes to see how engaged the owners or users of the Mailboxes are, by seeing how engaged in the conversation that are happening in the Mailbox. eg


The FindConversation operation in Exchange will return information such as the MessageCount and Size in a particular folder as well as the GlobalCount and Sizes across all folders in a Mailbox for a conversation.This is sample of a script that uses the findconversation operation to do some statistical sampling of conversation data. So what this does is

  • Does a FindConversation on the Inbox folder to grab the conversation information for the Inbox
  • Does a FindConversation on the SentItems Folder to grab the conversation stats for the Sent Mail
  • Combines the results together to work out the participation rate in the conversation based on the amount of Messages this particular mailbox sent.
  • For Exchange 2013 you can also query based on the received date of the email so you can look at the last 7 days worth or data etc.
So you can run the script like this to examine the whole of the Inbox

 .\converstats.ps1 user@domain.onmicrosoft.com

or you can use a Date to specify how much data you want to look at eg for the last 7 days use

.\converstats.ps1 user@domain.onmicrosoft.com (get-date).AddDays(-7)

In the script itself I've got it set to only report on conversation with a messagecount greater then 3 and sort the conversation by the participation rate you can adjust this by fiddling with the following line

$Script:rptcollection.Values | Where-Object {$_.InboxMessageCount -gt 3} | Sort-Object ParticipationRate -Descending | Export-Csv -NoTypeInformation -Path c:\Temp\$MailboxName-cnvStats.csv

I've put a download this script here the script itself looks like
  1. $MailboxName = $args[0]  
  2. $StartDate = $args[1]  
  3.   
  4.   
  5. ## Get the Mailbox to Access from the 1st commandline argument  
  6.   
  7. ## Load Managed API dll    
  8.   
  9. ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT  
  10. $EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")  
  11. if (Test-Path $EWSDLL)  
  12.     {  
  13.     Import-Module $EWSDLL  
  14.     }  
  15. else  
  16.     {  
  17.     "$(get-date -format yyyyMMddHHmmss):"  
  18.     "This script requires the EWS Managed API 1.2 or later."  
  19.     "Please download and install the current version of the EWS Managed API from"  
  20.     "http://go.microsoft.com/fwlink/?LinkId=255472"  
  21.     ""  
  22.     "Exiting Script."  
  23.     exit  
  24.     }  
  25.     
  26. ## Set Exchange Version    
  27. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2013_SP1  
  28.     
  29. ## Create Exchange Service Object    
  30. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  31.     
  32. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  33.     
  34. #Credentials Option 1 using UPN for the windows Account    
  35. $psCred = Get-Credential    
  36. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  37. $service.Credentials = $creds        
  38.     
  39. #Credentials Option 2    
  40. #service.UseDefaultCredentials = $true    
  41.     
  42. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  43.     
  44. ## Code From http://poshcode.org/624  
  45. ## Create a compilation environment  
  46. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  47. $Compiler=$Provider.CreateCompiler()  
  48. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  49. $Params.GenerateExecutable=$False  
  50. $Params.GenerateInMemory=$True  
  51. $Params.IncludeDebugInformation=$False  
  52. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  53.   
  54. $TASource=@' 
  55.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  56.     public class TrustAll : System.Net.ICertificatePolicy { 
  57.       public TrustAll() {  
  58.       } 
  59.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  60.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  61.         System.Net.WebRequest req, int problem) { 
  62.         return true; 
  63.       } 
  64.     } 
  65.   } 
  66. '@   
  67. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  68. $TAAssembly=$TAResults.CompiledAssembly  
  69.   
  70. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  71. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  72. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  73.   
  74. ## end code from http://poshcode.org/624  
  75.     
  76. ## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use    
  77.     
  78. #CAS URL Option 1 Autodiscover    
  79. $service.AutodiscoverUrl($MailboxName,{$true})    
  80. "Using CAS Server : " + $Service.url     
  81.      
  82. #CAS URL Option 2 Hardcoded    
  83.     
  84. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  85. #$service.Url = $uri      
  86.     
  87. ## Optional section for Exchange Impersonation    
  88.     
  89. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  90. if($StartDate -ne $null){  
  91.     $AQSString = "received:>" + $StartDate.ToString("yyyy-MM-dd")   
  92.     $AQSString  
  93. }  
  94. # Bind to the Inbox Folder  
  95. $Script:rptcollection = @{}  
  96. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  97. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  98. # Bind to the SentItems Folder  
  99. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SentItems,$MailboxName)     
  100. $SentItems = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  101.   
  102. function Process-Folder{    
  103.     param (    
  104.             $FolderId = "$( throw 'SMTPAddress is a mandatory Parameter' )",  
  105.             $IsSentItems = "$( throw 'SMTPAddress is a mandatory Parameter' )"  
  106.           )    
  107.     process{   
  108.         $cnvItemView = New-Object Microsoft.Exchange.WebServices.Data.ConversationIndexedItemView(1000)  
  109.         $cnvs = $null;  
  110.         do  
  111.         {  
  112.             $cnvs = $service.FindConversation($cnvItemView$FolderId,$AQSString);  
  113.             "Number of Conversation returned " + $cnvs.Count  
  114.             foreach($cnv in $cnvs){  
  115.                 $rptobj = $cnv | select Topic,LastDeliveryTime,UniqueSenders,UniqueRecipients,InboxMessageCount,GlobalMessageCount,InboxMessageSize,SentItemsMessageCount,SentItemsMessageSize,ParticipationRate      
  116.                 if($Script:rptcollection.Contains($cnv.Id.UniqueId)-eq $false){  
  117.                     if($IsSentItems){  
  118.                         $rptobj.SentItemsMessageCount = $cnv.MessageCount  
  119.                         $rptobj.SentItemsMessageSize = $cnv.Size  
  120.                         $rptobj.InboxMessageCount = 0  
  121.                         $rptobj.InboxMessageSize = 0  
  122.                         $rptobj.LastDeliveryTime = $cnv.LastDeliveryTime  
  123.                         $rptobj.UniqueSenders = $cnv.GlobalUniqueSenders  
  124.                         $rptobj.UniqueRecipients = $cnv.GlobalUniqueRecipients  
  125.                     }  
  126.                     else{  
  127.                         $rptobj.InboxMessageCount = $cnv.MessageCount  
  128.                         $rptobj.InboxMessageSize = $cnv.Size  
  129.                         $rptobj.SentItemsMessageCount = 0  
  130.                         $rptobj.SentItemsMessageSize = 0  
  131.                         $rptobj.LastDeliveryTime = $cnv.LastDeliveryTime  
  132.                         $rptobj.UniqueSenders = $cnv.GlobalUniqueSenders  
  133.                         $rptobj.UniqueRecipients = $cnv.GlobalUniqueRecipients  
  134.                     }  
  135.                     $Script:rptcollection.Add($cnv.Id.UniqueId,$rptobj)  
  136.                 }  
  137.                 else{  
  138.                     if($IsSentItems){  
  139.                         $Script:rptcollection[$cnv.Id.UniqueId].SentItemsMessageCount = $cnv.MessageCount  
  140.                         $Script:rptcollection[$cnv.Id.UniqueId].SentItemsMessageSize = $cnv.Size  
  141.                     }  
  142.                     else{  
  143.                         $Script:rptcollection[$cnv.Id.UniqueId].InboxMessageCount = $cnv.MessageCount  
  144.                         $Script:rptcollection[$cnv.Id.UniqueId].InboxMessageSize = $cnv.Size  
  145.                     }  
  146.                        
  147.                 }                 
  148.               
  149.             }  
  150.             $cnvItemView.Offset += $cnvs.Count  
  151.         }while($cnvs.Count -gt 0)  
  152.     }  
  153. }  
  154. Process-Folder -FolderId $Inbox.Id -IsSentItems $false  
  155. Process-Folder -FolderId $SentItems.Id -IsSentItems $true  
  156. foreach($value in $Script:rptcollection.Values){  
  157.     if($value.GlobalMessageCount -gt 0 -band $value.SentItemsMessageCount -gt 0){  
  158.         $value.ParticipationRate = [Math]::round((($value.SentItemsMessageCount/$value.GlobalMessageCount) * 100))  
  159.     }  
  160.     else{  
  161.         $value.ParticipationRate = 0  
  162.     }  
  163. }  
  164. $Script:rptcollection.Values | Where-Object {$_.InboxMessageCount -gt 3} | Sort-Object ParticipationRate -Descending | Export-Csv -NoTypeInformation -Path c:\Temp\$MailboxName-cnvStats.csv  
  165.    

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...

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You ...

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 ...
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.