Skip to main content

Junk Email SCL report using EWS and Powershell

Dealing with Junk Email is kind of like doing the dishes, it's dirty work but somebodies got to do it. While Spam filters are improving we know by the constant updates these filters require its an invisible war that's always going on. Also software being what it is, things don't always go to plan like this http://support.microsoft.com/kb/2885002/en-us

So it can be good to check in on what's happening in your User's JunkEmail folders from time to time and EWS is great for doing this so.

The following EWS script scans all the messages in the JunkEmail folder of a Mailbox (or Mailboxes) and looks at the SCL value of each of the Messages which is held in the

PidTagContentFilterSpamConfidenceLevel property

And also looks at the

PidLidSpamOriginalFolder property which contains the original folder a Message was moved from, which only gets set when the Outlook Junk Email Filter takes an action on a message vs the Server Side action (where this properties doesn't get set)

This script produces a report that shows the number of message for each SCL levels, total number of messages in the JunkEmail folder and the number of Messages move just by just Outlook Filter eg.


To run the script you need to feed it with a CSV with the mailbox you want to run it against something like

SmtpAddress
user@domain.com
user2@domain.com

Then use .\sclReport.pst .\users.csv

I've put a download of the script here

The script looks like

  1. $Script:rptCollection = @()    
  2.   
  3. ## Load Managed API dll    
  4. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  5.     
  6. ## Set Exchange Version    
  7. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  8.     
  9. ## Create Exchange Service Object    
  10. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  11.     
  12. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  13.     
  14. #Credentials Option 1 using UPN for the windows Account    
  15. $psCred = Get-Credential    
  16. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  17. $service.Credentials = $creds        
  18.     
  19. #Credentials Option 2    
  20. #service.UseDefaultCredentials = $true    
  21.     
  22. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  23.     
  24. ## Code From http://poshcode.org/624  
  25. ## Create a compilation environment  
  26. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  27. $Compiler=$Provider.CreateCompiler()  
  28. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  29. $Params.GenerateExecutable=$False  
  30. $Params.GenerateInMemory=$True  
  31. $Params.IncludeDebugInformation=$False  
  32. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  33.   
  34. $TASource=@' 
  35.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  36.     public class TrustAll : System.Net.ICertificatePolicy { 
  37.       public TrustAll() {  
  38.       } 
  39.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  40.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  41.         System.Net.WebRequest req, int problem) { 
  42.         return true; 
  43.       } 
  44.     } 
  45.   } 
  46. '@   
  47. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  48. $TAAssembly=$TAResults.CompiledAssembly  
  49.   
  50. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  51. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  52. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  53.   
  54. ## end code from http://poshcode.org/624  
  55.     
  56. ## 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    
  57.     
  58. #CAS URL Option 2 Hardcoded    
  59.     
  60. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  61. #$service.Url = $uri      
  62.     
  63. ## Optional section for Exchange Impersonation    
  64.     
  65. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $SmtpAddress)   
  66.   
  67. function Process-Mailbox{  
  68.     param (  
  69.             $SmtpAddress = "$( throw 'SMTPAddress is a mandatory Parameter' )"  
  70.           )  
  71.     process{  
  72.         Write-Host ("Processing Mailbox : " + $SmtpAddress)  
  73.         $rptObj = "" | select MailboxName,TotalItems,MovedByOutlook,NoSCL,SCLneg1,SCL0,SCL1,SCL2,SCL3,SCL4,SCL5,SCL6,SCL7,SCL8,SCL9  
  74.         $rptObj.MovedByOutlook = 0  
  75.         $rptObj.NoSCL = 0  
  76.         $rptObj.SCLneg1 = 0  
  77.         $rptObj.SCL0 = 0  
  78.         $rptObj.SCL1 = 0  
  79.         $rptObj.SCL2 = 0  
  80.         $rptObj.SCL3 = 0  
  81.         $rptObj.SCL4 = 0  
  82.         $rptObj.SCL5 = 0  
  83.         $rptObj.SCL6 = 0  
  84.         $rptObj.SCL7 = 0  
  85.         $rptObj.SCL8 = 0  
  86.         $rptObj.SCL9 = 0  
  87.         # Bind to the Junk Email Folder  
  88.         $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::JunkEmail,$SmtpAddress)     
  89.         $JunkEmail = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  90.         $rptObj.MailboxName = $SmtpAddress  
  91.         $rptObj.TotalItems = $JunkEmail.TotalCount  
  92.         $psPropset= new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)  
  93.         $PidTagContentFilterSpamConfidenceLevel = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x4076, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Integer)  
  94.         $PidLidSpamOriginalFolder = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x859C, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  95.         $psPropset.Add($PidTagContentFilterSpamConfidenceLevel)  
  96.         $psPropset.Add($PidLidSpamOriginalFolder)  
  97.         #Define ItemView to retrive just 1000 Items      
  98.         $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)    
  99.         $ivItemView.PropertySet = $psPropset  
  100.         $fiItems = $null      
  101.         do{      
  102.             $fiItems = $service.FindItems($JunkEmail.Id,$ivItemView)      
  103.             #[Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  104.             foreach($Item in $fiItems.Items){  
  105.                 $OrigFldVal = $null  
  106.                 if($Item.TryGetProperty($PidLidSpamOriginalFolder,[ref]$OrigFldVal)){  
  107.                     $rptObj.MovedByOutlook +=1  
  108.                 }  
  109.                 $SCLVal = $null;  
  110.                 if($Item.TryGetProperty($PidTagContentFilterSpamConfidenceLevel,[ref]$SCLVal)){  
  111.                     switch($SCLVal){  
  112.                         {$_ -lt 0}{$rptObj.SCLneg1 += 1}  
  113.                         0 { $rptObj.SCL0 += 1 }  
  114.                         1 { $rptObj.SCL1 += 1 }  
  115.                         2 { $rptObj.SCL2 += 1 }  
  116.                         3 { $rptObj.SCL3 += 1 }               
  117.                         4 { $rptObj.SCL4 += 1 }  
  118.                         5 { $rptObj.SCL5 += 1 }  
  119.                         6 { $rptObj.SCL6 += 1 }  
  120.                         7 { $rptObj.SCL7 += 1 }  
  121.                         8 { $rptObj.SCL8 += 1 }               
  122.                         9 { $rptObj.SCL9 += 1 }  
  123.                     }  
  124.                 }  
  125.                 else{  
  126.                     $rptObj.NoSCL +=1  
  127.                 }                          
  128.             }      
  129.             $ivItemView.Offset += $fiItems.Items.Count      
  130.         }while($fiItems.MoreAvailable -eq $true)   
  131.         $Script:rptCollection += $rptObj  
  132.     }  
  133. }  
  134.   
  135. Import-Csv -Path $args[0] | ForEach-Object{  
  136.     if($service.url -eq $null){  
  137.         $service.AutodiscoverUrl($_.SmtpAddress,{$true})   
  138.         "Using CAS Server : " + $Service.url   
  139.     }  
  140.     Try{  
  141.         Process-Mailbox -SmtpAddress $_.SmtpAddress  
  142.     }  
  143.     catch{  
  144.         LogWrite("Error processing Mailbox : " + $_.SmtpAddress + $_.Exception.Message.ToString())  
  145.     }  
  146. }  
  147. $Script:rptCollection | Export-Csv -NoTypeInformation -Path c:\temp\sclReport.csv  


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-

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

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