Skip to main content

Using Sender Flags in EWS

Sender Flags are an Outlook Feature that allow you to set a follow up flag on Message when your sending it as well as being able to set a Recipient Followup flag if you want to. (eg)


What happens in Exchange when you set a Sender Flag on a Message is documented in the Informational Flagging Protocol document http://msdn.microsoft.com/en-us/library/cc433487(v=exchg.80).aspx . If you want to do the same thing to a Message your sending in EWS there is nothing in the strongly typed classes to help out so you need to manually set two of the extended properties that are documented in that protocol document before you send the message and the Store will do the rest on submit. (More specifically what happens with the properties involved is documented here http://msdn.microsoft.com/en-us/library/ee217246(v=exchg.80).aspx )

The important properties that are involved with sender flags are the PidTagSwappedToDoData which is used to Store the information about what sender flags your want (eg in Outlook configured via the above dialogue box).  This is a binary property containing an number of Flags, The text for the Message Flags and the DateTime values for the Start and DueDate. The full structure of the property is documented in http://msdn.microsoft.com/en-us/library/ee201575(v=exchg.80).aspx

The DateTime values used in this Property are stored as a 4-byte integer that are expressed as the number of minutes since 00:00:00 on January 1, 1601, in UTC. To get this Integer the method I used is a TimeSpan between the Date you want and January 1, 1601, in UTC, you can then get the TotalMinutes for the timespan as an Integer.

 TimeSpan ts = new DateTime(2013,12,01,0,0,0,0,DateTimeKind.Utc) - new DateTime(1601, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);

The other important property is the PidTagSwappedToDoStore which is used by the Store after the Message is submitted. To use this is EWS you need to construct it based on the format documented in http://msdn.microsoft.com/en-us/library/ee203516%28v=exchg.80%29.aspx . The information necessary for this can be obtain through AutoDiscover. 

I've created a Powershell and EWS Sample for setting a Sender Flag on a Message with a Start and DueDate. I've put a download of this script here the code itself looks like

  1. ## Get the Mailbox to Access from the 1st commandline argument  
  2.   
  3. $MailboxName = $args[0]  
  4.   
  5. $SenderFlagText = "This is a Test Blah Blah"  
  6. $FlagStartDate = (Get-Date).AddDays(1)  
  7. $FlagDueDate = (Get-Date).AddDays(7)  
  8.  
  9.  
  10. ## Load Managed API dll    
  11. Add-Type -Path "C:\Program Files\Microsoft\Exchange\Web Services\2.0\Microsoft.Exchange.WebServices.dll"    
  12.    
  13. ## Set Exchange Version    
  14. $ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2    
  15.    
  16. ## Create Exchange Service Object    
  17. $service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)    
  18.    
  19. ## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials    
  20.    
  21. #Credentials Option 1 using UPN for the windows Account    
  22. $psCred = Get-Credential    
  23. $creds = New-Object System.Net.NetworkCredential($psCred.UserName.ToString(),$psCred.GetNetworkCredential().password.ToString())    
  24. $service.Credentials = $creds        
  25.    
  26. #Credentials Option 2    
  27. #service.UseDefaultCredentials = $true    
  28.    
  29. ## Choose to ignore any SSL Warning issues caused by Self Signed Certificates    
  30.    
  31. ## Code From http://poshcode.org/624  
  32. ## Create a compilation environment  
  33. $Provider=New-Object Microsoft.CSharp.CSharpCodeProvider  
  34. $Compiler=$Provider.CreateCompiler()  
  35. $Params=New-Object System.CodeDom.Compiler.CompilerParameters  
  36. $Params.GenerateExecutable=$False  
  37. $Params.GenerateInMemory=$True  
  38. $Params.IncludeDebugInformation=$False  
  39. $Params.ReferencedAssemblies.Add("System.DLL") | Out-Null  
  40.   
  41. $TASource=@' 
  42.   namespace Local.ToolkitExtensions.Net.CertificatePolicy{ 
  43.     public class TrustAll : System.Net.ICertificatePolicy { 
  44.       public TrustAll() {  
  45.       } 
  46.       public bool CheckValidationResult(System.Net.ServicePoint sp, 
  47.         System.Security.Cryptography.X509Certificates.X509Certificate cert,  
  48.         System.Net.WebRequest req, int problem) { 
  49.         return true; 
  50.       } 
  51.     } 
  52.   } 
  53. '@   
  54. $TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)  
  55. $TAAssembly=$TAResults.CompiledAssembly  
  56.  
  57. ## We now create an instance of the TrustAll and attach it to the ServicePointManager  
  58. $TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")  
  59. [System.Net.ServicePointManager]::CertificatePolicy=$TrustAll  
  60.  
  61. ## end code from http://poshcode.org/624  
  62.    
  63. ## 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    
  64.    
  65. #CAS URL Option 1 Autodiscover    
  66. $service.AutodiscoverUrl($MailboxName,{$true})    
  67. "Using CAS Server : " + $Service.url     
  68.     
  69. #CAS URL Option 2 Hardcoded    
  70.    
  71. #$uri=[system.URI] "https://casservername/ews/exchange.asmx"    
  72. #$service.Url = $uri      
  73.    
  74. ## Optional section for Exchange Impersonation    
  75.   
  76. function hex2binarray($hexString){  
  77.     $i = 0  
  78.     [byte[]]$binarray = @()  
  79.     while($i -le $hexString.length - 2){  
  80.         $strHexBit = ($hexString.substring($i,2))  
  81.         $binarray += [byte]([Convert]::ToInt32($strHexBit,16))  
  82.         $i = $i + 2  
  83.     }  
  84.     return ,$binarray  
  85. }  
  86.   
  87. function GetAutoDiscoverSettings{  
  88.     param (  
  89.             $adEmailAddress = "$( throw 'emailaddress is a mandatory Parameter' )",  
  90.             $Credentials = "$( throw 'Credentials is a mandatory Parameter' )"  
  91.           )  
  92.     process{  
  93.         $adService = New-Object Microsoft.Exchange.WebServices.AutoDiscover.AutodiscoverService($ExchangeVersion);  
  94.         $adService.Credentials = $Credentials  
  95.         $adService.EnableScpLookup = $false;  
  96.         $adService.RedirectionUrlValidationCallback = {$true}  
  97.         $UserSettings = new-object Microsoft.Exchange.WebServices.Autodiscover.UserSettingName[] 3  
  98.         $UserSettings[0] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN  
  99.         $UserSettings[1] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer  
  100.         $UserSettings[2] = [Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDisplayName  
  101.         $adResponse = $adService.GetUserSettings($adEmailAddress , $UserSettings);  
  102.         return $adResponse  
  103.     }  
  104. }  
  105. function GetAddressBookId{  
  106.     param (  
  107.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  108.           )  
  109.     process{  
  110.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  111.         $userdnHexChar = $userdnString.ToCharArray();  
  112.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  113.         $Provider = "00000000DCA740C8C042101AB4B908002B2FE1820100000000000000"  
  114.         $userdnStringHex = $Provider + $userdnStringHex + "00"  
  115.         return $userdnStringHex  
  116.     }  
  117. }  
  118. function GetStoreId{  
  119.     param (  
  120.             $AutoDiscoverSettings = "$( throw 'AutoDiscoverSettings is a mandatory Parameter' )"  
  121.           )  
  122.     process{  
  123.         $userdnString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::UserDN]  
  124.         $userdnHexChar = $userdnString.ToCharArray();  
  125.         foreach ($element in $userdnHexChar) {$userdnStringHex = $userdnStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}   
  126.         $serverNameString = $AutoDiscoverSettings.Settings[[Microsoft.Exchange.WebServices.Autodiscover.UserSettingName]::InternalRpcClientServer]  
  127.         $serverNameHexChar = $serverNameString.ToCharArray();  
  128.         foreach ($element in $serverNameHexChar) {$serverNameStringHex = $serverNameStringHex + [System.String]::Format("{0:X}", [System.Convert]::ToUInt32($element))}  
  129.         $flags = "00000000"  
  130.         $ProviderUID = "38A1BB1005E5101AA1BB08002B2A56C2"  
  131.         $versionFlag = "0000"  
  132.         $DLLFileName = "454D534D44422E444C4C00000000"  
  133.         $WrappedFlags = "00000000"  
  134.         $WrappedProviderUID = "1B55FA20AA6611CD9BC800AA002FC45A"  
  135.         $WrappedType = "0C000000"  
  136.         $StoredIdStringHex = $flags + $ProviderUID + $versionFlag + $DLLFileName + $WrappedFlags + $WrappedProviderUID + $WrappedType + $serverNameStringHex + "00" + $userdnStringHex + "00"  
  137.         return $StoredIdStringHex  
  138.     }  
  139. }  
  140.   
  141.   
  142. function GetPidTagSwappedToDoData {  
  143.     param (  
  144.         $FlagText = "$( throw 'FlagText is a mandatory Parameter' )",  
  145.         $StartTime = "$( throw 'StartTime is a mandatory Parameter' )",  
  146.         $DueTime = "$( throw 'DueTime is a mandatory Parameter' )"  
  147.     )  
  148.     process{  
  149.         $todoTimeFlagged  = "01000000";  
  150.         $PidLidFlagRequest = ""  
  151.         $PidLidFlagRequestHexChar = $FlagText.ToCharArray();  
  152.         $PidLidFlagRequest = [System.BitConverter]::ToString([System.Text.UnicodeEncoding]::Unicode.GetBytes($FlagText)).Replace("-","")  
  153.         #Pad Flag to 512 Bytes  
  154.         for ($padCnt = $PidLidFlagRequest.Length / 2; $padCnt -lt 512; $padCnt++) {  
  155.                 $PidLidFlagRequest = $PidLidFlagRequest + "00";  
  156.         }  
  157.         $stime = New-Object System.DateTime $StartTime.Year,$StartTime.Month,$StartTime.Day,0,0,0,0,Utc  
  158.         $dtime =  New-Object System.DateTime $DueTime.Year,$DueTime.Month,$DueTime.Day,0,0,0,0,Utc  
  159.         $etime = New-Object System.DateTime 1601, 1, 1, 0, 0, 0, 0,Utc  
  160.         [System.TimeSpan]$StartDateTimets = $stime - $etime  
  161.         [System.TimeSpan]$DateDueTimets = $dtime - $etime  
  162.         $HexDateStartTime = [System.Convert]::ToInt64($StartDateTimets.TotalMinutes).ToString("X8");  
  163.         $HexDateStartTime = $HexDateStartTime.Substring(6, 2) + $HexDateStartTime.Substring(4, 2) + $HexDateStartTime.Substring(2, 2) + $HexDateStartTime.Substring(0, 2);  
  164.         $HexDateDueTime = [System.Convert]::ToInt64($DateDueTimets.TotalMinutes).ToString("X8");  
  165.         $HexDateDueTime = $HexDateDueTime.Substring(6, 2) + $HexDateDueTime.Substring(4, 2) + $HexDateDueTime.Substring(2, 2) + $HexDateDueTime.Substring(0, 2);  
  166.         $ulVersion = "01000000";  
  167.         $dwFlags = "79000000"; #dwToDoItem,rtmStartDate,rtmDueDate ,wszFlagTo ,fReminderSet   
  168.         $dwToDoItem = $todoTimeFlagged;  
  169.         $wszFlagTo = $PidLidFlagRequest;  
  170.         $rtmStartDate = $HexDateStartTime;  
  171.         $rtmDueDate = $HexDateDueTime;  
  172.         $rtmReminder = "00000000";  
  173.         $fReminderSet = "00000000";  
  174.         return ($ulVersion + $dwFlags + $dwToDoItem + $wszFlagTo + $rtmStartDate + $rtmDueDate + $rtmReminder + $fReminderSet);  
  175.     }  
  176. }  
  177.  
  178. #$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)   
  179. $SenderFlagEmail = New-Object Microsoft.Exchange.WebServices.Data.EmailMessage -ArgumentList $service    
  180. $SenderFlagEmail.ToRecipients.Add("glenscales@yahoo.com");  
  181. $SenderFlagEmail.Subject = "test";  
  182. $SenderFlagEmail.Body =  New-Object  Microsoft.Exchange.WebServices.Data.MessageBody([Microsoft.Exchange.WebServices.Data.BodyType]::HTML,"test");  
  183. $PR_SWAPPED_TODO_DATA = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E2D,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary);  
  184. $PR_SWAPPED_TODO_STORE = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E2C,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary);  
  185.   
  186. $adset = GetAutoDiscoverSettings -adEmailAddress $MailboxName -Credentials $creds  
  187. $storeID = ""  
  188. if($adset -is [Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverResponse]){  
  189.     Write-Host ("Get StoreId")  
  190.     $storeID = GetStoreId -AutoDiscoverSettings $adset  
  191. }  
  192.   
  193. $senderFlagHex = GetPidTagSwappedToDoData -FlagText $SenderFlagText -StartTime $FlagStartDate  -DueTime $FlagDueDate  
  194.   
  195. $SenderFlagEmail.SetExtendedProperty($PR_SWAPPED_TODO_DATA,(hex2binarray $senderFlagHex));  
  196. $SenderFlagEmail.SetExtendedProperty($PR_SWAPPED_TODO_STORE,(hex2binarray $storeID));  
  197. $SenderFlagEmail.SendAndSaveCopy();  
  198. Write-Host ("Message Sent")  


Popular posts from this blog

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

Sending a Message in Exchange Online via REST from an Arduino MKR1000

This is part 2 of my MKR1000 article, in this previous post  I looked at sending a Message via EWS using Basic Authentication.  In this Post I'll look at using the new Outlook REST API  which requires using OAuth authentication to get an Access Token. The prerequisites for this sketch are the same as in the other post with the addition of the ArduinoJson library  https://github.com/bblanchon/ArduinoJson  which is used to parse the Authentication Results to extract the Access Token. Also the SSL certificates for the login.windows.net  and outlook.office365.com need to be uploaded to the devices using the wifi101 Firmware updater. To use Token Authentication you need to register an Application in Azure https://msdn.microsoft.com/en-us/office/office365/howto/add-common-consent-manually  with the Mail.Send permission. The application should be a Native Client app that use the Out of Band Callback urn:ietf:wg:oauth:2.0:oob. You need to authorize it in you tenant (eg build a small ap

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.