Friday, September 05, 2014

Creating a Mailbox alias usage report with EWS and Powershell

Before starting this one I want to point out the method I'm going to demonstrate in this post is not the best method to use to do this. If you have Message Tracking available then you can do this much more accurately using the Message tracking logs.  But if you don't have this available to you or you just want to see what you can do with EWS then this is the post for you.

Many people have one or more email addresses assigned to their mailboxes (they get referred to using different names alias's, proxyaddress's, secondary address's, alternate address's etc) but in Outlook and OWA it can be hard to see what email address has been used to send you a mail because of the delivery process and the way the addresses are resolved. To get the actual email address a particular email was sent to one workaround you can use in EWS is to use the PidTagTransportMessageHeaders property and then parse the TO, CC and BCC Headers (note generally the BCC header won't be there even if you have been BCC'd) from the transport headers.

So what this script does is first it uses the Exchange Management Shell's get-mailbox cmdlet to grab all proxyaddresses for the target account. This is needed because there is noway in EWS to get all the Mailbox proxy addresses (you can use ResolveName to get the Mailbox Contact from AD but you will only get returned the first 3 addresses for the mailbox). It stores these addresses in a hashtable that can then be used in to do lookups so when processing all the emailaddress in header we can filter to only build a report of the current mailboxes addresses being used. The next part of the code is some normal EWS fair to grab all the messages in the Inbox for the last 7 days and then grab the PidTagTransportMessageHeaders  property and parse the TO,CC and BCC addresses from the headers using a linear parser and some RegEX (I know some people don't like linear parsing but I always find they work well).  The script then builds two reports the first report is a summary report showing each of the alias's that where used and how many TO,CC and BCC where used eg



The other report that the script builds is an Item Report which shows for each Item in the Inbox which method was used eg


Now as I mentioned there are a few problems with the method used in the script if you have been BCC'd on a message generally there won't be any information in the headers to reflect which email address was used. Also if the message was sent to a Distribution list or it's a piece of GrayMail depending on whatever method the mailer has used there maybe no header. So in this case it will show other in the method and the last parsed TO address.

To run this script you need to have a Remote Powershell session open so you can run Get-Mailbox and then just run the script with the PrimaryEmaillAddress of the mailbox you want to run the script against as a parameter. The script will output the two reports to the temp directory

I've put a download of this script here the code looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. $Mailbox = get-mailbox $MailboxName  
  6. $mbAddress = @{}  
  7. foreach($emEmail in $Mailbox.EmailAddresses){  
  8.     if($emEmail.Tolower().Contains("smtp:")){  
  9.         $mbAddress.Add($emEmail.SubString(5).Tolower(),0)  
  10.     }  
  11. }  
  12.   
  13. ## Load Managed API dll    
  14.   
  15. ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT  
  16. $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")  
  17. if (Test-Path $EWSDLL)  
  18.     {  
  19.     Import-Module $EWSDLL  
  20.     }  
  21. else  
  22.     {  
  23.     "$(get-date -format yyyyMMddHHmmss):"  
  24.     "This script requires the EWS Managed API 1.2 or later."  
  25.     "Please download and install the current version of the EWS Managed API from"  
  26.     "http://go.microsoft.com/fwlink/?LinkId=255472"  
  27.     ""  
  28.     "Exiting Script."  
  29.     exit  
  30.     }  
  31.     
  32. ## Set Exchange Version    
  33. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  34.     
  35. ## Create Exchange Service Object    
  36. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  37.     
  38. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  39.     
  40. #Credentials Option 1 using UPN for the windows Account    
  41. $psCred = Get-Credential    
  42. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  43. $service.Credentials = $creds        
  44.     
  45. #Credentials Option 2    
  46. #service.UseDefaultCredentials = $true    
  47.     
  48. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  49.     
  50. ## Code From http://poshcode.org/624  
  51. ## Create a compilation environment  
  52. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  53. $Compiler=$Provider.CreateCompiler()  
  54. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  55. $Params.GenerateExecutable=$False  
  56. $Params.GenerateInMemory=$True  
  57. $Params.IncludeDebugInformation=$False  
  58. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  59.   
  60. $TASource=@' 
  61.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  62.     public class TrustAll : System.Net.ICertificatePolicy { 
  63.       public TrustAll() {  
  64.       } 
  65.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  66.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  67.         System.Net.WebRequest req, int problem) { 
  68.         return true; 
  69.       } 
  70.     } 
  71.   } 
  72. '@   
  73. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  74. $TAAssembly=$TAResults.CompiledAssembly  
  75.   
  76. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  77. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  78. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  79.   
  80. ## end code from http://poshcode.org/624  
  81.     
  82. ## 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    
  83.     
  84. #CAS URL Option 1 Autodiscover    
  85. $service.AutodiscoverUrl($MailboxName,{$true})    
  86. "Using CAS Server : " + $Service.url     
  87.      
  88. #CAS URL Option 2 Hardcoded    
  89.     
  90. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  91. #$service.Url = $uri      
  92.     
  93. ## Optional section for Exchange Impersonation    
  94.     
  95. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  96.   
  97. # Bind to the Inbox Folder  
  98. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  99. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  100. $PR_TRANSPORT_MESSAGE_HEADERS = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x007D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);  
  101. $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)    
  102. $psPropset.Add($PR_TRANSPORT_MESSAGE_HEADERS)  
  103. $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)  
  104. $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Size)  
  105. $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)  
  106. #Define ItemView to retrive just 1000 Items      
  107. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  108. $ivItemView.PropertySet = $psPropset  
  109. $rptCollection = @()  
  110. $rptcntCount = @{}  
  111. #Find Items that are unread  
  112. $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, (Get-Date).AddDays(-7));   
  113. $fiItems = $null      
  114. do{      
  115.     $fiItems = $service.FindItems($Inbox.Id,$sfItemSearchFilter,$ivItemView)      
  116.     [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  117.     foreach($Item in $fiItems.Items){      
  118.         $Headers = $null;  
  119.         $Address = "";  
  120.         $Method = ""  
  121.         if($Item.TryGetProperty($PR_TRANSPORT_MESSAGE_HEADERS,[ref]$Headers)){  
  122.             $slen = $Headers.ToLower().IndexOf("`nto: ")  
  123.             if($slen -gt 0){  
  124.                 $elen = $Headers.IndexOf("`r`n",$slen)                
  125.                 $ToAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))  
  126.                 while($Headers.Substring($elen+2,1) -eq [char]9){  
  127.                     $slen = $elen+2  
  128.                     $elen = $Headers.IndexOf("`r`n",$slen)    
  129.                     $ToAddressParsed += $Headers.SubString(($slen),$elen-($slen))  
  130.                 }  
  131.                 $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);  
  132.                 $emailMatches = $emailRegex.Matches($ToAddressParsed);  
  133.                 foreach($Match in $emailMatches){  
  134.                     if($mbAddress.Contains($Match.Value.Tolower())){  
  135.                         $Address = $Match  
  136.                         $Method = "To"  
  137.                         if($rptcntCount.ContainsKey($Match.Value)){  
  138.                             $rptcntCount[$Match.Value].To +=1  
  139.                         }  
  140.                         else{  
  141.                             $rptObj = "" | Select Address,To,CC,BCC  
  142.                             $rptObj.Address = $Match.Value  
  143.                             $rptObj.To = 1  
  144.                             $rptObj.CC = 0  
  145.                             $rptObj.BCC = 0  
  146.                             $rptcntCount.Add($Match.Value,$rptObj)                    
  147.                         }  
  148.                     }  
  149.                     else{  
  150.                         if($Address -eq ""){  
  151.                             $Address = $Match  
  152.                             $Method = "Other"  
  153.                         }  
  154.                     }  
  155.                 }  
  156.             }  
  157.             $slen = $Headers.ToLower().IndexOf("`ncc: ")  
  158.             if($slen -gt 0){  
  159.                 $elen = $Headers.IndexOf("`r`n",$slen)  
  160.                 $ccAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))  
  161.                 while($Headers.Substring($elen+2,1) -eq [char]9){  
  162.                     $slen = $elen+2  
  163.                     $elen = $Headers.IndexOf("`r`n",$slen)    
  164.                     $ccAddressParsed += $Headers.SubString(($slen),$elen-($slen))  
  165.                 }  
  166.                 $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);  
  167.                 $emailMatches = $emailRegex.Matches($ccAddressParsed);  
  168.                 foreach($Match in $emailMatches){  
  169.                     if($mbAddress.Contains($Match.Value.Tolower())){  
  170.                         $Address = $Match  
  171.                         $Method = "CC"  
  172.                         if($rptcntCount.ContainsKey($Match.Value)){  
  173.                             $rptcntCount[$Match.Value].CC +=1  
  174.                         }  
  175.                         else{  
  176.                             $rptObj = "" | Select Address,To,CC,BCC  
  177.                             $rptObj.Address = $Match.Value  
  178.                             $rptObj.To = 0  
  179.                             $rptObj.CC = 1  
  180.                             $rptObj.BCC = 0  
  181.                             $rptcntCount.Add($Match.Value,$rptObj)                    
  182.                         }  
  183.                     }  
  184.                 }  
  185.             }  
  186.             $slen = $Headers.ToLower().IndexOf("`nbcc: ")  
  187.             if($slen -gt 0){  
  188.                 $elen = $Headers.IndexOf("`r`n",$slen)  
  189.                 $bccAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))  
  190.                 while($Headers.Substring($elen+2,1) -eq [char]9){  
  191.                     $slen = $elen+2  
  192.                     $elen = $Headers.IndexOf("`r`n",$slen)    
  193.                     $bccAddressParsed += $Headers.SubString(($slen),$elen-($slen))  
  194.                 }  
  195.                 $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);  
  196.                 $emailMatches = $emailRegex.Matches($bccAddressParsed);  
  197.                 foreach($Match in $emailMatches){  
  198.                     if($mbAddress.Contains($Match.Value.Tolower())){  
  199.                         $Address = $Match  
  200.                         $Method = "BCC"  
  201.                         if($rptcntCount.ContainsKey($Match.Value)){  
  202.                             $rptcntCount[$Match.Value].BCC +=1  
  203.                         }  
  204.                         else{  
  205.                             $rptObj = "" | Select Address,To,CC,BCC  
  206.                             $rptObj.Address = $Match.Value  
  207.                             $rptObj.To = 0  
  208.                             $rptObj.CC = 0  
  209.                             $rptObj.BCC = 1  
  210.                             $rptcntCount.Add($Match.Value,$rptObj)                    
  211.                         }  
  212.                     }  
  213.                 }  
  214.             }  
  215.         }  
  216.         $ItemReport = "" | Select DateTimeReceived,Method,Address,Subject,Size  
  217.         $ItemReport.DateTimeReceived = $Item.DateTimeReceived  
  218.         $ItemReport.Subject = $Item.Subject  
  219.         $ItemReport.Size = $Item.Size  
  220.         $ItemReport.Method = $Method  
  221.         $ItemReport.Address = $Address  
  222.         $rptCollection += $ItemReport  
  223.           
  224.     }      
  225.     $ivItemView.Offset += $fiItems.Items.Count  
  226.     Write-Host ("Processed " + $ivItemView.Offset + " of " + $fiItems.TotalCount)  
  227. }while($fiItems.MoreAvailable -eq $true)   
  228. $rptcntCount.Values | ft  
  229. $rptcntCount.Values | Export-Csv -NoTypeInformation -path "c:\Temp\$MailboxName-MHSummaryReport.csv"  
  230. $rptCollection | Export-Csv -NoTypeInformation -path "c:\Temp\$MailboxName-MHItemReport.csv"  

No comments: