Wednesday, September 17, 2014

Sending a No Reply, No ReplyAll, No Forward Email using EWS and Powershell

I've you haven't seen this before Gavin Smyth from Microsoft Research put together this cool VSTO plugin to allow you to send an Email from Outlook that will disable the Reply, ReplyAll and Forward Buttons on the Outlook ribbon http://research.microsoft.com/en-us/projects/researchdesktop/noreplyall.aspx and the how to posts about the VSTO http://blogs.msdn.com/b/gsmyth/archive/2011/09/18/noreply-vsto-add-in-wrap-up.aspx .

Note this only works in Outlook (not OWA or ActiveSync etc) but basically what a users would see when they receive a message is



How this works is it sets the PidLidVerbStream Property on a message which is mostly documented in the http://msdn.microsoft.com/en-us/library/ee218541(v=exchg.80).aspx protocol document. I say mostly because the format you get when using the methods from the NoReply Addin is a little different from the format documented which is for Voting buttons but its good enough to work with. The Verbs that this property refers to are the standard Verbs that MAPI implements which are documented in http://msdn.microsoft.com/en-us/library/office/cc815879(v=office.15).aspx .

So to use this same property in an EWS script you can just set it using the Extended Properties, the value you use is a little tricky as only the voteoption format is fully documented. But because this is pretty standard you can cut a past the Hex Values which contains the two streams from this property out of an existing message and then just change the bits that either enables or disable the Verbs for what you want to enable or disable on the Message your sending.

So this is what the following script does is allows you to send a message using EWS and set the options to enable and disable each of these verbs.

In the script I've got the following custom object where you can set the verbs on or off
  1. $VerbSetting = "" | Select DisableReplyAll,DisableReply,DisableForward,DisableReplyToFolder  
  2. $VerbSetting.DisableReplyAll = $true  
  3. $VerbSetting.DisableReply = $true  
  4. $VerbSetting.DisableForward = $true  
  5. $VerbSetting.DisableReplyToFolder = $true  

The rest of the script builds the VerbStream value property based on the setting in the custom object and the rest of the script is a standard EWS script to send a message.

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

  1. $MailboxName = $args[0]  
  2. $SentTo = $args[1]  
  3.   
  4. $VerbSetting = "" | Select DisableReplyAll,DisableReply,DisableForward,DisableReplyToFolder  
  5. $VerbSetting.DisableReplyAll = $true  
  6. $VerbSetting.DisableReply = $true  
  7. $VerbSetting.DisableForward = $true  
  8. $VerbSetting.DisableReplyToFolder = $true  
  9.   
  10. ## Load Managed API dll    
  11.   
  12. ###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT  
  13. $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")  
  14. if (Test-Path $EWSDLL)  
  15.     {  
  16.     Import-Module $EWSDLL  
  17.     }  
  18. else  
  19.     {  
  20.     "$(get-date -format yyyyMMddHHmmss):"  
  21.     "This script requires the EWS Managed API 1.2 or later."  
  22.     "Please download and install the current version of the EWS Managed API from"  
  23.     "http://go.microsoft.com/fwlink/?LinkId=255472"  
  24.     ""  
  25.     "Exiting Script."  
  26.     exit  
  27.     }  
  28.     
  29. ## Set Exchange Version    
  30. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  31.     
  32. ## Create Exchange Service Object    
  33. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  34.     
  35. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  36.     
  37. #Credentials Option 1 using UPN for the windows Account    
  38. $psCred = Get-Credential    
  39. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  40. $service.Credentials = $creds        
  41.     
  42. #Credentials Option 2    
  43. #service.UseDefaultCredentials = $true    
  44.     
  45. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  46.     
  47. ## Code From http://poshcode.org/624  
  48. ## Create a compilation environment  
  49. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  50. $Compiler=$Provider.CreateCompiler()  
  51. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  52. $Params.GenerateExecutable=$False  
  53. $Params.GenerateInMemory=$True  
  54. $Params.IncludeDebugInformation=$False  
  55. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  56.   
  57. $TASource=@' 
  58.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  59.     public class TrustAll : System.Net.ICertificatePolicy { 
  60.       public TrustAll() {  
  61.       } 
  62.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  63.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  64.         System.Net.WebRequest req, int problem) { 
  65.         return true; 
  66.       } 
  67.     } 
  68.   } 
  69. '@   
  70. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  71. $TAAssembly=$TAResults.CompiledAssembly  
  72.   
  73. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  74. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  75. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  76.   
  77. ## end code from http://poshcode.org/624  
  78.     
  79. ## 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    
  80.     
  81. #CAS URL Option 1 Autodiscover    
  82. $service.AutodiscoverUrl($MailboxName,{$true})    
  83. "Using CAS Server : " + $Service.url     
  84.      
  85. #CAS URL Option 2 Hardcoded    
  86.     
  87. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  88. #$service.Url = $uri      
  89.     
  90. ## Optional section for Exchange Impersonation    
  91.     
  92. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  93.   
  94.   
  95. function Get-VerbStream{    
  96.     param (    
  97.             $VerbSettings = "$( throw 'VerbSettings is a mandatory Parameter' )"    
  98.           )    
  99.     process{    
  100.       
  101.     $Header = "02010400000000000000"  
  102.     $ReplyToAllHeader = "055265706C790849504D2E4E6F7465074D657373616765025245050000000000000000"  
  103.     $ReplyToAllFooter = "0000000000000002000000660000000200000001000000"  
  104.     $ReplyToHeader = "0C5265706C7920746F20416C6C0849504D2E4E6F7465074D657373616765025245050000000000000000"  
  105.     $ReplyToFooter = "0000000000000002000000670000000300000002000000"  
  106.     $ForwardHeader = "07466F72776172640849504D2E4E6F7465074D657373616765024657050000000000000000"  
  107.     $ForwardFooter = "0000000000000002000000680000000400000003000000"  
  108.     $ReplyToFolderHeader = "0F5265706C7920746F20466F6C6465720849504D2E506F737404506F737400050000000000000000"  
  109.     $ReplyToFolderFooter = "00000000000000020000006C00000008000000"  
  110.     $VoteOptionExtras = "0401055200650070006C00790002520045000C5200650070006C007900200074006F00200041006C006C0002520045000746006F007200770061007200640002460057000F5200650070006C007900200074006F00200046006F006C0064006500720000"  
  111.     if($VerbSetting.DisableReplyAll){  
  112.         $DisableReplyAllVal = "00"  
  113.     }  
  114.     else{  
  115.         $DisableReplyAllVal = "01"  
  116.     }  
  117.     if($VerbSetting.DisableReply){  
  118.         $DisableReplyVal = "00"  
  119.     }  
  120.     else{  
  121.         $DisableReplyVal = "01"  
  122.     }  
  123.     if($VerbSetting.DisableForward){  
  124.         $DisableForwardVal = "00"  
  125.     }  
  126.     else{  
  127.         $DisableForwardVal = "01"  
  128.     }  
  129.     if($VerbSetting.DisableReplyToFolder){  
  130.         $DisableReplyToFolderVal = "00"  
  131.     }  
  132.     else{  
  133.         $DisableReplyToFolderVal = "01"  
  134.     }  
  135.     $VerbValue = $Header +  $ReplyToAllHeader + $DisableReplyAllVal + $ReplyToAllFooter + $ReplyToHeader + $DisableReplyVal +$ReplyToFooter + $ForwardHeader + $DisableForwardVal + $ForwardFooter + $ReplyToFolderHeader + $DisableReplyToFolderVal + $ReplyToFolderFooter + $VoteOptionExtras  
  136.     return $VerbValue  
  137.     }  
  138. }  
  139.   
  140. function hex2binarray($hexString){  
  141.     $i = 0  
  142.     [byte[]]$binarray = @()  
  143.     while($i -le $hexString.length - 2){  
  144.         $strHexBit = ($hexString.substring($i,2))  
  145.         $binarray += [byte]([Convert]::ToInt32($strHexBit,16))  
  146.         $i = $i + 2  
  147.     }  
  148.     return ,$binarray  
  149. }  
  150.   
  151.   
  152.   
  153. $VerbStreamProp = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::Common,0x8520, [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)  
  154.   
  155. $VerbSettingValue = get-VerbStream $VerbSetting  
  156.   
  157. $EmailMessage = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service    
  158. $EmailMessage.Subject = "Message Subject"    
  159. #Add Recipients      
  160. $EmailMessage.ToRecipients.Add($SentTo)    
  161. $EmailMessage.Body = New-Object Microsoft.Exchange.WebServices.Data.MessageBody    
  162. $EmailMessage.Body.BodyType = [Microsoft.Exchange.WebServices.Data.BodyType]::HTML    
  163. $EmailMessage.Body.Text = "Body"   
  164. $EmailMessage.SetExtendedProperty($VerbStreamProp,(hex2binarray $VerbSettingValue))  
  165. $EmailMessage.SendAndSaveCopy()    

4 comments:

Anonymous said...

Is there a way to do it from EWS API? (Java)

Nicolas Duran said...

Is there a way to do it from EWS API? (Java)

Glen Scales said...

Sure just set the same properties I don't use the Java API but I believe the methods objects are the same

Anonymous said...

how to do this in c# .net? Thanks