Skip to main content

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"  

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is.

I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned)

#Define Date to Query
$StartDate = (Get-Date)
$EndDate = (Ge…

EWS Managed API and Powershell How-To series Part 1

I thought I'd start the year with a series of posts that goes back over the basics of using the EWS Managed API from Powershell and provides a modular remarked example that you can easily cut and paste to build your own scripts. Along the way in this series I'll show a whole bunch of examples around specific things.

As a starting point for versions this will be Powershell Version 2.0  and the EWS Managed API 1.1 (which will soon change to 1.2 once released) http://www.microsoft.com/download/en/details.aspx?id=13480.

The starting point for any EWS script your going to write is connecting to Exchange for which there are three important pieces of information you will need. Firstly you need to know the version of Exchange your running in this script its going to be held in the following variable

$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1

Other valid values for Exchange 2007 would be

$ExchangeVersion = [Microsoft.Exchange.WebServices.…

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script.

So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this …
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.