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
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
- ## Get the Mailbox to Access from the 1st commandline argument
- $MailboxName = $args[0]
- $Mailbox = get-mailbox $MailboxName
- $mbAddress = @{}
- foreach($emEmail in $Mailbox.EmailAddresses){
- if($emEmail.Tolower().Contains("smtp:")){
- $mbAddress.Add($emEmail.SubString(5).Tolower(),0)
- }
- }
- ## Load Managed API dll
- ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
- $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")
- if (Test-Path $EWSDLL)
- {
- Import-Module $EWSDLL
- }
- else
- {
- "$(get-date -format yyyyMMddHHmmss):"
- "This script requires the EWS Managed API 1.2 or later."
- "Please download and install the current version of the EWS Managed API from"
- "http://go.microsoft.com/fwlink/?LinkId=255472"
- ""
- "Exiting Script."
- exit
- }
- ## Set Exchange Version
- $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2
- ## Create Exchange Service Object
- $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)
- ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials
- #Credentials Option 1 using UPN for the windows Account
- $psCred = Get-Credential
- $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())
- $service.Credentials = $creds
- #Credentials Option 2
- #service.UseDefaultCredentials = $true
- ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates
- ## Code From http://poshcode.org/624
- ## Create a compilation environment
- $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
- $Compiler=$Provider.CreateCompiler()
- $Params=New-Object System.CodeDom.Compiler.CompilerParameters
- $Params.GenerateExecutable=$False
- $Params.GenerateInMemory=$True
- $Params.IncludeDebugInformation=$False
- $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null
- $TASource=@'
- namespace Local.ToolkitExtensions.Net.CertificatePolicy{
- public class TrustAll : System.Net.ICertificatePolicy {
- public TrustAll() {
- }
- public bool CheckValidationResult(System.Net.ServicePoint sp,
- System.Security.Cryptography.X509Certificates.X509Certificate cert,
- System.Net.WebRequest req, int problem) {
- return true;
- }
- }
- }
- '@
- $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
- $TAAssembly=$TAResults.CompiledAssembly
- ## We now create an instance of the TrustAll and attach it to the ServicePointManager
- $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
- [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll
- ## end code from http://poshcode.org/624
- ## 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
- #CAS URL Option 1 Autodiscover
- $service.AutodiscoverUrl($MailboxName,{$true})
- "Using CAS Server : " + $Service.url
- #CAS URL Option 2 Hardcoded
- #$uri=[system.URI] "https://casservername/ews/exchange.asmx"
- #$service.Url = $uri
- ## Optional section for Exchange Impersonation
- #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
- # Bind to the Inbox Folder
- $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
- $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
- $PR_TRANSPORT_MESSAGE_HEADERS = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x007D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String);
- $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::IdOnly)
- $psPropset.Add($PR_TRANSPORT_MESSAGE_HEADERS)
- $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
- $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::Size)
- $psPropset.Add([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived)
- #Define ItemView to retrive just 1000 Items
- $ivItemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
- $ivItemView.PropertySet = $psPropset
- $rptCollection = @()
- $rptcntCount = @{}
- #Find Items that are unread
- $sfItemSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsGreaterThan([Microsoft.Exchange.WebServices.Data.ItemSchema]::DateTimeReceived, (Get-Date).AddDays(-7));
- $fiItems = $null
- do{
- $fiItems = $service.FindItems($Inbox.Id,$sfItemSearchFilter,$ivItemView)
- [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)
- foreach($Item in $fiItems.Items){
- $Headers = $null;
- $Address = "";
- $Method = ""
- if($Item.TryGetProperty($PR_TRANSPORT_MESSAGE_HEADERS,[ref]$Headers)){
- $slen = $Headers.ToLower().IndexOf("`nto: ")
- if($slen -gt 0){
- $elen = $Headers.IndexOf("`r`n",$slen)
- $ToAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))
- while($Headers.Substring($elen+2,1) -eq [char]9){
- $slen = $elen+2
- $elen = $Headers.IndexOf("`r`n",$slen)
- $ToAddressParsed += $Headers.SubString(($slen),$elen-($slen))
- }
- $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);
- $emailMatches = $emailRegex.Matches($ToAddressParsed);
- foreach($Match in $emailMatches){
- if($mbAddress.Contains($Match.Value.Tolower())){
- $Address = $Match
- $Method = "To"
- if($rptcntCount.ContainsKey($Match.Value)){
- $rptcntCount[$Match.Value].To +=1
- }
- else{
- $rptObj = "" | Select Address,To,CC,BCC
- $rptObj.Address = $Match.Value
- $rptObj.To = 1
- $rptObj.CC = 0
- $rptObj.BCC = 0
- $rptcntCount.Add($Match.Value,$rptObj)
- }
- }
- else{
- if($Address -eq ""){
- $Address = $Match
- $Method = "Other"
- }
- }
- }
- }
- $slen = $Headers.ToLower().IndexOf("`ncc: ")
- if($slen -gt 0){
- $elen = $Headers.IndexOf("`r`n",$slen)
- $ccAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))
- while($Headers.Substring($elen+2,1) -eq [char]9){
- $slen = $elen+2
- $elen = $Headers.IndexOf("`r`n",$slen)
- $ccAddressParsed += $Headers.SubString(($slen),$elen-($slen))
- }
- $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);
- $emailMatches = $emailRegex.Matches($ccAddressParsed);
- foreach($Match in $emailMatches){
- if($mbAddress.Contains($Match.Value.Tolower())){
- $Address = $Match
- $Method = "CC"
- if($rptcntCount.ContainsKey($Match.Value)){
- $rptcntCount[$Match.Value].CC +=1
- }
- else{
- $rptObj = "" | Select Address,To,CC,BCC
- $rptObj.Address = $Match.Value
- $rptObj.To = 0
- $rptObj.CC = 1
- $rptObj.BCC = 0
- $rptcntCount.Add($Match.Value,$rptObj)
- }
- }
- }
- }
- $slen = $Headers.ToLower().IndexOf("`nbcc: ")
- if($slen -gt 0){
- $elen = $Headers.IndexOf("`r`n",$slen)
- $bccAddressParsed = $Headers.SubString(($slen+4),$elen-($slen+4))
- while($Headers.Substring($elen+2,1) -eq [char]9){
- $slen = $elen+2
- $elen = $Headers.IndexOf("`r`n",$slen)
- $bccAddressParsed += $Headers.SubString(($slen),$elen-($slen))
- }
- $emailRegex = new-object System.Text.RegularExpressions.Regex("\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*",[System.Text.RegularExpressions.RegexOptions]::IgnoreCase);
- $emailMatches = $emailRegex.Matches($bccAddressParsed);
- foreach($Match in $emailMatches){
- if($mbAddress.Contains($Match.Value.Tolower())){
- $Address = $Match
- $Method = "BCC"
- if($rptcntCount.ContainsKey($Match.Value)){
- $rptcntCount[$Match.Value].BCC +=1
- }
- else{
- $rptObj = "" | Select Address,To,CC,BCC
- $rptObj.Address = $Match.Value
- $rptObj.To = 0
- $rptObj.CC = 0
- $rptObj.BCC = 1
- $rptcntCount.Add($Match.Value,$rptObj)
- }
- }
- }
- }
- }
- $ItemReport = "" | Select DateTimeReceived,Method,Address,Subject,Size
- $ItemReport.DateTimeReceived = $Item.DateTimeReceived
- $ItemReport.Subject = $Item.Subject
- $ItemReport.Size = $Item.Size
- $ItemReport.Method = $Method
- $ItemReport.Address = $Address
- $rptCollection += $ItemReport
- }
- $ivItemView.Offset += $fiItems.Items.Count
- Write-Host ("Processed " + $ivItemView.Offset + " of " + $fiItems.TotalCount)
- }while($fiItems.MoreAvailable -eq $true)
- $rptcntCount.Values | ft
- $rptcntCount.Values | Export-Csv -NoTypeInformation -path "c:\Temp\$MailboxName-MHSummaryReport.csv"
- $rptCollection | Export-Csv -NoTypeInformation -path "c:\Temp\$MailboxName-MHItemReport.csv"