Saturday, November 24, 2012

Create an RSS feed of Exchange Items using any of the How To Series scripts

If you've missed my HowTo Series this year I've been demonstrating many different way's of getting, filtering and searching for Exchange data using Powershell and the EWS Managed API see the full list here . One of the fun things to do with scripting is to link this together with the other plethora of script's out in the world to do different things. Here one example of linking the How-To series script with an RSS feed script from the PoshCode repository http://poshcode.org/?show=669

The following script grabs the last 50 Items in the Inbox and creates an RSS feed of theses Item including Links to OWA for the Item and the Item's Body as HTML in the Feed details.

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

  1. ###Code from http://poshcode.org/?show=669  
  2. # Creates an RSS feed  
  3. # Parameter input is for "site": Path, Title, Url, Description  
  4. # Pipeline input is for feed items: hashtable with Title, Link, Author, Description, and pubDate keys  
  5. Function New-RssFeed  
  6. {   
  7.     param (  
  8.             $Path = "$( throw 'Path is a mandatory parameter.' )",  
  9.             $Title = "Site Title",  
  10.             $Url = "http://$( $env:computername )",  
  11.             $Description = "Description of site"  
  12.     )  
  13.     Begin {  
  14.             # feed metadata  
  15.             $encoding = [System.Text.Encoding]::UTF8  
  16.             $writer = New-Object System.Xml.XmlTextWriter( $Path$encoding )  
  17.             $writer.WriteStartDocument()  
  18.             $writer.WriteStartElement( "rss" )  
  19.             $writer.WriteAttributeString( "version""2.0" )  
  20.             $writer.WriteStartElement( "channel" )  
  21.             $writer.WriteElementString( "title"$Title )  
  22.             $writer.WriteElementString( "link"$Url )  
  23.             $writer.WriteElementString( "description"$Description )  
  24.     }  
  25.     Process {  
  26.             # Construct feed items  
  27.             $writer.WriteStartElement( "item" )  
  28.             $writer.WriteElementString( "title",    $_.title )  
  29.             $writer.WriteElementString( "link",             $_.link )  
  30.             $writer.WriteElementString( "author",   $_.author )  
  31.             $writer.WriteStartElement( "description" )  
  32.             $writer.WriteRaw( "<![CDATA[" ) # desc can contain HTML, so its escaped using SGML escape code  
  33.             $writer.WriteRaw( $_.description )  
  34.             $writer.WriteRaw( "]]>" )  
  35.             $writer.WriteEndElement()  
  36.             $writer.WriteElementString( "pubDate"$_.pubDate.toString( 'r' ) )  
  37.             $writer.WriteElementString( "guid"$homePageUrl + "/" + [guid]::NewGuid() )  
  38.             $writer.WriteEndElement()  
  39.     }  
  40.     End {  
  41.             $writer.WriteEndElement()  
  42.             $writer.WriteEndElement()  
  43.             $writer.WriteEndDocument()  
  44.             $writer.Close()  
  45.     }  
  46. }  
  47. ### end code from http://poshcode.org/?show=669  
  48.   
  49. ## Get the Mailbox to Access from the 1st commandline argument  
  50.   
  51. $MailboxName = $args[0]  
  52.   
  53. ## Load Managed API dll    
  54. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  55.     
  56. ## Set Exchange Version    
  57. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1    
  58.     
  59. ## Create Exchange Service Object    
  60. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  61.     
  62. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  63.     
  64. #Credentials Option 1 using UPN for the windows Account    
  65. $psCred = Get-Credential    
  66. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  67. $service.Credentials = $creds        
  68.     
  69. #Credentials Option 2    
  70. #service.UseDefaultCredentials = $true    
  71.     
  72. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  73.     
  74. ## Code From http://poshcode.org/624  
  75. ## Create a compilation environment  
  76. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  77. $Compiler=$Provider.CreateCompiler()  
  78. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  79. $Params.GenerateExecutable=$False  
  80. $Params.GenerateInMemory=$True  
  81. $Params.IncludeDebugInformation=$False  
  82. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  83.   
  84. $TASource=@' 
  85.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  86.     public class TrustAll : System.Net.ICertificatePolicy { 
  87.       public TrustAll() {  
  88.       } 
  89.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  90.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  91.         System.Net.WebRequest req, int problem) { 
  92.         return true; 
  93.       } 
  94.     } 
  95.   } 
  96. '@   
  97. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  98. $TAAssembly=$TAResults.CompiledAssembly  
  99.   
  100. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  101. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  102. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  103.   
  104. ## end code from http://poshcode.org/624  
  105.     
  106. ## 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    
  107.     
  108. #CAS URL Option 1 Autodiscover    
  109. $service.AutodiscoverUrl($MailboxName,{$true})    
  110. "Using CAS Server : " + $Service.url     
  111.      
  112. #CAS URL Option 2 Hardcoded    
  113.     
  114. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  115. #$service.Url = $uri      
  116.     
  117. ## Optional section for Exchange Impersonation    
  118.     
  119. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  120.   
  121. # Bind to the Contacts Folder  
  122.   
  123. $folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)     
  124. $Inbox = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)  
  125. $psPropset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties)    
  126. #Define ItemView to retrive just 50 Items      
  127. $ivItemView =  New-Object Microsoft.Exchange.WebServices.Data.ItemView(50)      
  128. $fiItems = $service.FindItems($Inbox.Id,$ivItemView)      
  129. [Void]$service.LoadPropertiesForItems($fiItems,$psPropset)    
  130. $feedItems = @()  
  131. foreach($Item in $fiItems.Items){      
  132.      "processing Item " + $Item.Subject  
  133.      $PostItem = @{}  
  134.      $PostItem.Add("Title",$Item.Subject)  
  135.      $PostItem.Add("Author",$Item.Sender.Address)  
  136.      $PostItem.Add("pubDate",$Item.DateTimeReceived)  
  137.      $PostItem.Add("link",("https://" + $service.Url.Host +  "/owa/" + $Item.WebClientReadFormQueryString))  
  138.      $PostItem.Add("description",$Item.Body.Text)  
  139.      $feedItems += $PostItem         
  140. }      
  141. $feedItems | New-RssFeed -path "c:\temp\Inboxfeed.xml" -title ($MailboxName + " Inbox")  


Thursday, November 15, 2012

Using eDiscovery to search mailboxes using EWS in Exchange 2013 (the new Exchange)

eDiscovery is one of the new features in Exchange 2013 that has been built on the top of new operations added in Exchange Web Services in 2013. While its very useful for ITPro's for handling legal discoveries and compliance issues, it opens up a whole new world for application developers building Apps that search Exchange Mailboxes. Like the AQS querystring that was introduced in Exchange 2010 the eDiscovery operations make use of the Exchange Search service's content indexes.

There isn't much documentation around at the moment about how to use eDiscovery in EWS so this is just a dump of what I've learned so far.

All up there are four new EWS operations for eDiscovery however the two that you will use most of the time would be.



GetSearchableMailboxes
Gets a list of mailboxes that the client has permission to search or perform eDiscovery on.
SearchMailboxes
Searches for items in specific mailboxes that match query keywords.

from http://msdn.microsoft.com/en-us/library/exchange/jj190897.aspx

Permissions wise you need to be a member of the Discovery Management RBAC role

The eDiscovery operations make use of the Keyword Query Language (KQL) which there is some decent documentation for in the Protocol documents for KQL http://msdn.microsoft.com/en-us/library/hh644280%28v=office.12%29.aspx although this isn't very Exchange specific. KQL is pretty cool and gives greater control and functionality over the queries you make when compared against AQS. The syntax does bare similarities to AQS and in some cases your AQS queries should just be transferable.

Some KQL samples would be

Subject:"New Time Proposed: test"  -  This would do an exact match on the Subject

Subject:Football    - This would do a SubString type query on the Subject

attachment:'.pdf'  - The would search for attachment with a pdf attachment

To use the new eDisocvery operations in the EWS Managed API you need to have v2.0 which was released recently http://www.microsoft.com/en-au/download/details.aspx?id=35371 .

So now it comes to using the SearchMaiboxes operation, to do this you need to have a properly formated KQL query and you need to know the Mailbox Identifier to use. The Mailbox identifier was a bit of tricky one where in most other things in EWS this would be the PrimarySMTPAddress, for this operation its the X500 (or legacyExchangedn) of the mailbox. There are a few ways you could get this the eaiest and most reliable would be to use the GetSearchableMailboxes operation to build the MailboxSearchScope array for the mailboxes you want to search . eg

  1. GetSearchableMailboxesResponse gsMBResponse = service.GetSearchableMailboxes("fsmith"false);  
  2. MailboxSearchScope[] msbScope = new MailboxSearchScope[gsMBResponse.SearchableMailboxes.Length];  
  3. Int32 mbCount = 0;  
  4. foreach (SearchableMailbox sbMailbox in gsMBResponse.SearchableMailboxes) {  
  5.     msbScope[mbCount] = new MailboxSearchScope(sbMailbox.ReferenceId, MailboxSearchLocation.All);  
  6.     mbCount++;  
  7. }  
The Important point is the ReferenceId (which is the X500 address) is the Id that SearchMailbox seems to want.
Next you build the actually request

  1. SearchMailboxesParameters smSearchMailbox = new SearchMailboxesParameters();  
  2. MailboxQuery mbq = new MailboxQuery("attachment:'.pdf'", msbScope);  
  3. MailboxQuery[] mbqa = new MailboxQuery[1] { mbq };  
  4. smSearchMailbox.SearchQueries = mbqa;  
  5. smSearchMailbox.PageSize = 1000;  
  6. smSearchMailbox.ResultType = Microsoft.Exchange.WebServices.Data.SearchResultType.PreviewOnly;  
  7. service.TraceEnabled = true;  
  8. ServiceResponseCollection<SearchMailboxesResponse> srCol =  service.SearchMailboxes(smSearchMailbox);  
There are a bunch of options for manipulating the results such as deduplication and the ability to page and sort the results in different ways and orders. You can also choose just to return the statistics of the query without the results, or return the resutls as PreviewItems where you can control what properties are returned in the PreviewItem.

So for me its a big thumbs up for eDiscovery, so far anyway I can see some frustrations in the way the PriviewItems are returned and there needs to be a lot better info for using KQL and the discovery options.

Monday, November 12, 2012

Creating a sender domain auto reply rule for a mailbox with EWS and Powershell

This is a rewrite of an old CDO 1.2 rule.dll script back from 2006 http://gsexdev.blogspot.com.au/2006/10/creating-domain-based-auto-response.html .

Creating a Domain based auto response rule allows you to have a custom auto-responder for an email based on the sender's email domain of any newly received email messages. This is useful when you need to cater for a number of different scenarios and where you want to add a more personal touch to these auto responders. 

EWS allows you to create Inbox rules via the CreateRule Operation if your after the full spiel have a read of http://msdn.microsoft.com/en-us/library/exchange/hh298418%28v=exchg.140%29.aspx

In this script it first uses a ContainsSenderStrings condition to filter on the domain you want the rule to apply to in my example yahoo.com

$nrNewInboxRule.Conditions.ContainsSenderStrings.Add("@yahoo.com")

Exceptions are created for any messages with subject prefixes of RE and FW to omit these messages from an Auto-Response.

$nrNewInboxRule.Exceptions.ContainsSubjectStrings.Add("RE:");
$nrNewInboxRule.Exceptions.ContainsSubjectStrings.Add("FW:")

The script also creates the auto response message which is a message that is saved in the Assoicated Items collection of the Inbox with a message class of "IPM.Note.Rules.ReplyTemplate.Microsoft". One important thing is to set the PidTagReplyTemplateId property on the Template messages as per http://msdn.microsoft.com/en-us/library/ff367988%28v=EXCHG.80%29.aspx 

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

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. ## Load Managed API dll    
  6. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll"    
  7.     
  8. ## Set Exchange Version    
  9. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  10.     
  11. ## Create Exchange Service Object    
  12. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  13.     
  14. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  15.     
  16. #Credentials Option 1 using UPN for the windows Account    
  17. $psCred = Get-Credential    
  18. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  19. $service.Credentials = $creds        
  20.     
  21. #Credentials Option 2    
  22. #service.UseDefaultCredentials = $true    
  23.     
  24. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  25.     
  26. ## Code From http://poshcode.org/624  
  27. ## Create a compilation environment  
  28. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  29. $Compiler=$Provider.CreateCompiler()  
  30. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  31. $Params.GenerateExecutable=$False  
  32. $Params.GenerateInMemory=$True  
  33. $Params.IncludeDebugInformation=$False  
  34. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  35.   
  36. $TASource=@' 
  37.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  38.     public class TrustAll : System.Net.ICertificatePolicy { 
  39.       public TrustAll() {  
  40.       } 
  41.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  42.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  43.         System.Net.WebRequest req, int problem) { 
  44.         return true; 
  45.       } 
  46.     } 
  47.   } 
  48. '@   
  49. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  50. $TAAssembly=$TAResults.CompiledAssembly  
  51.   
  52. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  53. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  54. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  55.   
  56. ## end code from http://poshcode.org/624  
  57.     
  58. ## 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    
  59.     
  60. #CAS URL Option 1 Autodiscover    
  61. $service.AutodiscoverUrl($MailboxName,{$true})    
  62. "Using CAS Server : " + $Service.url     
  63.      
  64. #CAS URL Option 2 Hardcoded    
  65.     
  66. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  67. #$service.Url = $uri      
  68.     
  69. ## Optional section for Exchange Impersonation    
  70.     
  71. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  72.   
  73. $tmTemplateEmail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service  
  74. $tmTemplateEmail.ItemClass = "IPM.Note.Rules.ReplyTemplate.Microsoft";  
  75. $tmTemplateEmail.IsAssociated = $true;  
  76. $tmTemplateEmail.Subject = "Recipient of your Email action required";  
  77. $htmlBodyString = "Hello,<p>Thanks for your Email we only answer emails enqiures from coperates email domains";  
  78. $tmTemplateEmail.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody($htmlBodyString);  
  79. $PidTagReplyTemplateId = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65C2, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  80. $tmTemplateEmail.SetExtendedProperty($PidTagReplyTemplateId, [System.Guid]::NewGuid().ToByteArray());  
  81. $tmTemplateEmail.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox);  
  82. $nrNewInboxRule = New-Object Microsoft.Exchange.WebServices.Data.Rule   
  83. $nrNewInboxRule.DisplayName = "Auto Reply Rule";  
  84. $nrNewInboxRule.Conditions.ContainsSenderStrings.Add("@yahoo.com")  
  85. $nrNewInboxRule.Actions.ServerReplyWithMessage = $tmTemplateEmail.Id;  
  86. $nrNewInboxRule.Exceptions.ContainsSubjectStrings.Add("RE:");  
  87. $nrNewInboxRule.Exceptions.ContainsSubjectStrings.Add("FW:");  
  88. $cnCreateNewRule = New-Object Microsoft.Exchange.WebServices.Data.createRuleOperation[] 1  
  89. $cnCreateNewRule[0] = $nrNewInboxRule  
  90. $service.UpdateInboxRules($cnCreateNewRule,$true);