InfiniTec - Henning Krauses Blog

Don't adjust your mind - it's reality that is malfunctioning

Setting the Homepage of an Exchange folder using the EWS Managed API

A while ago, Glen posted an article on his blog on how to set homepage of a folder using ADO and later he posted a version of that script which uses the EWS managed API to do this in this MSDN forum thread. However, he wrote it for the first version of the API, and the EWS Managed API 1.1 has a slightly different object model. Since someone on the MSDN forums had difficulties to update the script to work with the EWS Managed API 1.1, I thought I just post an updated version here:

private static void SetFolderHomePage(IEnumerable<string> pathFragments, string url, ExchangeService service)
    var folderWebviewinfoProperty = new ExtendedPropertyDefinition(14047, MapiPropertyType.Binary);
    var root = Folder.Bind(service, WellKnownFolderName.MsgFolderRoot);
    var targetFolder = root;
    foreach (var fragment in pathFragments)
        var result = service.FindFolders(targetFolder.Id, new SearchFilter.IsEqualTo(FolderSchema.DisplayName, fragment), new FolderView(1));
        if (result.TotalCount == 0)
            throw new InvalidOperationException(string.Format("Folder fragment {0} was not found.", fragment));
        targetFolder = result.Folders[0];

    targetFolder.SetExtendedProperty(folderWebviewinfoProperty, EncodeUrl(url));

private static byte[] EncodeUrl(string url)
    var writer = new StringWriter();
    var dataSize = ((ConvertToHex(url).Length / 2) + 2).ToString("X2");

    writer.Write("02"); // Version
    writer.Write("00000001"); // Type
    writer.Write("00000001"); // Flags
    writer.Write("00000000000000000000000000000000000000000000000000000000"); // unused
    var buffer = HexStringToByteArray(writer.ToString());
    return buffer;

private static string ConvertToHex(string input)
    return string.Join(string.Empty, input.Select(c => ((int) c).ToString("x2") + "00").ToArray());

private static byte[] HexStringToByteArray(string input)
    return Enumerable
        .Range(0, input.Length/2)
        .Select(index => byte.Parse(input.Substring(index*2, 2), NumberStyles.AllowHexSpecifier)).ToArray();

You can set the homepage of a folder by calling the SetFolderHomepage method:

SetFolderHomePage(service, new[] {"InfiniTec blog"},;

Posted by Henning Krause on Wednesday, October 5, 2011 7:30 PM, last modified on Wednesday, October 5, 2011 7:34 PM
Permalink | Post RSSRSS comment feed

FindItems Helper method for the Exchange Managed API

I’ve seen quite a few samples for using the FindItems method of the EWS Managed API, either on StackOverflow or in the Exchange development forum. One of the most common error I see is that people disable paging by specifying creating an ItemView like this:

var view = new ItemView(int.MaxValue);

Don’t do that! A query using this ItemView will put a severe burden on the Exchange server if the folder being queried contains many items. The pageSize parameter is there for a reason.

Instead of querying all items at once, one should do a proper paging: Query, say, 512 items and process them. Then, query the next 512 items. Thanks to iterators in C#, the process of retrieving the items can be completely separated away from the processing.

If you are not familiar with C# iterators, have a look at this article. In essence, the yield operator allows for deferred execution, something you might heard from with regards to LINQ.

Here is a helper method which uses this technique to iterate over the contents of an Exchange folder, requesting 512 items per batch and returning them to the caller. When used properly, this method uses very little resources on the Exchange server as well as on the client. Additionally, it allows for querying the body of an item. In this case, instead of executing a FindItems request, it executes a FindItems request and a LoadPropertiesForItems request per batch.

Due to the nature of the method, you should not put the items returned from the methods in a List, as this would consume a lot of memory on the client. Instead process the items one by one.

public static class ExchangeServiceExtension
    public static IEnumerable<Item> FindItems(this ExchangeService service, WellKnownFolderName folderName, PropertySet propertySet, SearchFilter searchFilter, ItemTraversal traversal = ItemTraversal.Shallow, params KeyValuePair<PropertyDefinition, SortDirection>[] orderBy)
        return FindItems(service, new FolderId(folderName), propertySet, searchFilter, traversal, orderBy);

    public static IEnumerable<Item> FindItems(this ExchangeService service, FolderId folderId, PropertySet propertySet, SearchFilter searchFilter = null, ItemTraversal traversal = ItemTraversal.Shallow, params KeyValuePair<PropertyDefinition, SortDirection>[] orderBy)
        if (service == null) throw new ArgumentNullException("service");
        if (folderId == null) throw new ArgumentNullException("folderId");
        if (propertySet == null) throw new ArgumentNullException("propertySet");

        PropertySet propertySetToQuery;

        // If the body or unique body is requested, the FindItems method cannot be used to query the 
        // propertyset. Instead a GetItem operation is required. The propertyset IdOnly is used in this case
        // for the FindItems operation.
        if (propertySet.Contains(ItemSchema.Body) || propertySet.Contains(ItemSchema.UniqueBody))
            propertySetToQuery = PropertySet.IdOnly;
            propertySetToQuery = propertySet;

        var itemView = new ItemView(512) { PropertySet = propertySetToQuery, Traversal = traversal };
        if (orderBy != null)
            foreach (var order in orderBy)
                itemView.OrderBy.Add(order.Key, order.Value);

        bool hasMoreItems;
            var result = service.FindItems(folderId, searchFilter, itemView);
            if (propertySetToQuery == PropertySet.IdOnly)
                // Load the properties, including the body using a GetItem request.
                service.LoadPropertiesForItems(result, propertySet);
            foreach (var item in result)
                yield return item;
            hasMoreItems = result.MoreAvailable;
            itemView.Offset += 512;
        } while (hasMoreItems);

As you can see, this method uses several .NET 4.0 features: Optional parameters and extension methods. So, if you are still using .NET 2.0, you’ll need to modify the code a little bit.

To use these methods, insert this code into your solution. In the class where you want to use the methods, add a using to the namespace containing the ExchangeServiceExtension. Both methods will then appear in the code completion window on instances of the ExchangeService class:


In the following example, the method is used to iterate over all items in the Inbox folder and printing the items to the console:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject));

foreach (var item in items)
    Console.Out.WriteLine("Subject = {0}", item.Subject);

Since the last parameters are optional, they can be omitted. This example adds a sort clause to the call:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject), 
    orderBy: new KeyValuePair<PropertyDefinition, SortDirection>(ItemSchema.Subject, SortDirection.Ascending));

Of course, a SearchFilter and an ItemTraversal can also be specified:

var items = service.FindItems(WellKnownFolderName.Inbox, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject), 
    new SearchFilter.ContainsSubstring(ItemSchema.Subject, "test"), ItemTraversal.Associated, 
    new KeyValuePair<PropertyDefinition, SortDirection>(ItemSchema.Subject, SortDirection.Ascending));

Posted by Henning Krause on Thursday, September 8, 2011 11:15 PM, last modified on Thursday, September 8, 2011 11:15 PM
Permalink | Post RSSRSS comment feed

Custom Mail headers and EWS

The mail headers are exposed on the EmailMessage as first class property: InternetMessageHeaders. However, Exchange also stores each mail header in its own property and defines a unique property set for it: PS_INTERNET_HEADERS.

Here is a property definition for a hypothetical custom property:

private static readonly ExtendedPropertyDefinition FrobProperty =
    new ExtendedPropertyDefinition(DefaultExtendedPropertySet.InternetHeaders, "X-Frob", MapiPropertyType.String);

If a mail is processed by Exchange with message header like this:

Subject: Test mail
X-Frob: Yes
From: "Henning Krause" <>
To: "Someone <someone@example.local>

Exchange will parse the mail and set the value of the extended property defined above to “Yes”.

Retrieving the custom property is as simple as this:

var item = Item.Bind(service, itemId,
    new PropertySet(BasePropertySet.FirstClassProperties, FrobProperty));

The value of the property can then be accessed using this line:

string frobValue;
if (item.TryGetProperty(FrobProperty, out frobValue))
    Console.Out.WriteLine("The item as a frob value of: {0}", frobValue);

You can even search for messages which have the header “X-Frob” set to “Yes”:

var itemId = folder.FindItems(new SearchFilter.IsEqualTo(FrobProperty, "yes"), 
    new ItemView(10) {PropertySet = PropertySet.IdOnly});

This query will return the first ten messages which have said header set to “Yes”.

Note that Exchange has a limit for named properties which are the result of custom mail headers. You may get one of these entries in your EventLog at some point:

Event ID: 9666
Type: Warning
Category: General
Source: msgidNamedPropsQuotaWarning
Description: The number of named properties created for database "<database name>" is close to quota limit. Current number of named properties: <number of named properties>. Quota limit for named properties: <configured quota>. User attempting to create the named property: <user name>. Named property GUID: <GUID of named property>. Named property name/id: <name of named property>.


Event ID: 9667
Type: Error
Category: General
Source: msgidNamedPropsQuotaError
Description: Failed to create a new named property for database "<database name>" because the number of named properties reached the quota limit (<configured quota>). User attempting to create the named property: <user name>. Named property GUID: <GUID of named property>. Named property name/id: <name of named property>.


See this blog post on how to deal with this issue:

Posted by Henning Krause on Monday, August 1, 2011 12:00 PM, last modified on Wednesday, July 27, 2011 5:57 PM
Permalink | Post RSSRSS comment feed

Working with the Master Category List–EWS edition

Back in 2008 I wrote an article about accessing the Master Category List using WebDAV. If you are not sure what the Master Category List is, read that article first…

EWS could not be used at that time, since access to the Folder Associated Items via EWS is a Feature of Exchange 2010. So if you are on Exchange 2007, the old article still applies.

The last article contained some code which simplified updating the list. I’ve updated the code and aligned the method naming with that of the EWS managed API.

This is the class diagram for the updated code:


The classes are really easy to use:

var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new NetworkCredential("", "password") };
service.AutodiscoverUrl("", url => true);

var list = MasterCategoryList.Bind(service);
foreach (var category in list.Categories)
    Console.Out.WriteLine("category = {0}", category.Name);

The only interesting line in the sample above is line 4. The call to MasterCategoryList.Bind() loads the MasterCategoryList from the users Exchange Mailbox. After that, the name of each console is written to the console.

Adding a new category is equally simple:

var service = new ExchangeService(ExchangeVersion.Exchange2010_SP1) { Credentials = new NetworkCredential("", "password") };
service.AutodiscoverUrl("", url => true);

var list = MasterCategoryList.Bind(service);
list.Categories.Add(new Category("Vacation", CategoryColor.DarkMaroon, CategoryKeyboardShortcut.CtrlF10));

This will add a new category named “Vacation” to the list.

So how does this work? The Master Category List is stored in a hidden message in the calendar folder of a mailbox. EWS in 2010 provides simple access to this message with the UserConfiguration class. This code show how the Master Category List is loaded:

var item = UserConfiguration.Bind(service, "CategoryList", WellKnownFolderName.Calendar,

var reader = new StreamReader(new MemoryStream(item.XmlData), Encoding.UTF8, true);

The configuration data is stored in the XmlData property as UTF-8 encoded byte array.

Here is the new code:

Sourcecode Download

Posted by Henning Krause on Thursday, July 28, 2011 4:00 PM, last modified on Tuesday, June 11, 2013 4:52 PM
Permalink | Post RSSRSS comment feed

How to get the number of unread mails from multiple mailboxes using the EWS Managed API and PowerShell

Interesting question in the Exchange development forum today: How do I get the number of unread messages in the inbox folder from a number of mailboxes? The questioner wants to send a text message to each owner of a mailbox notifying him of the number of unread mails in his inbox. The requirement was to do this with PowerShell. So, here is a quick solution for this problem:

param ([string] $inputFile, [System.Management.Automation.PSCredential] $credential)

$ErrorActionPreference = "Stop"

if (($inputFile -eq [String]::Empty) -or (Test-Path $inputFile) -eq $false) 
    throw "Invalid file specified ({0})." -f $inputFile

[Reflection.Assembly]::LoadFrom("C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll")

$service =  New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)

if ($credential -ne $null) 
    $service.Credentials = $credential.GetNetworkCredential()
    $service.UseDefaultCredentials = $true;

function GetUnreadInboxMails([string] $emailAddress) 
    $service.AutodiscoverUrl($emailAddress, {$true});
    $maibox = New-Object Microsoft.Exchange.WebServices.Data.Mailbox($emailAddress)
    $folderId = New-Object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox, $mailbox)
    $folder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service, $folderId);
    $result = New-Object PSObject -Property @{ 
        EmailAddress = $emailAddress
        UnreadMailCount=  $folder.UnreadCount;
    return $result;

function ProcessResult($entry) 
    "Mailbox: {0}" -f $entry.EmailAddress
    "Unread Mails: {0}" -f $entry.UnreadMailCount

$addresses = Import-Csv $inputFile

$addresses | % {GetUnreadInboxMails($_.MailAddress)}  | % {ProcessResult ($_)} 

Just paste this script into an editor and save it as ps1 file.

The script mainly consists of two function: GetUnreadInboxMails and ProcessResult. The former method retrieves the number of unread mails in the inbox of the mailbox of the specified user. The number of unread mails can be retrieved from a Folder instance: The UnreadCount property. The method returns the number of unread mails along with the mail address of the current mailbox. The other important function is the ProcessResult method. In this script it merely dumps the result to the console. The questioner in the post linked above can use this function to call his HTTP service to send a text message.

The script has two parameters:

  1. The name of a CSV file containing the list of mailboxes to process. The first line should contain the column name “MailAddress” somewhere. The following lines should contain the email address of the mailbox in this column.
  2. A PSCredential object containing valid credentials to use for the Exchange access.

The credential used for the script needs read access to the inbox folder of each mailbox specified in the file.

Posted by Henning Krause on Monday, July 25, 2011 7:56 PM, last modified on Monday, July 25, 2011 7:56 PM
Permalink | Post RSSRSS comment feed

Exchange Managed API autodiscover with Powershell

Powershell is a great tool to automate all sorts of things – including fiddling around with your Exchange mailbox. And the Autodiscover makes it really easy to connect to it – especially if you’re on Office 365 and don’t even know your CAS server.

So first, we need to load the EWS Managed API dll into the current runspace:

[Reflection.Assembly]::LoadFrom("C:\Program Files\Microsoft\Exchange\Web Services\1.1\Microsoft.Exchange.WebServices.dll")

Then, create an ExchangeService instance and set its credentials:

$service =  New-Object Microsoft.Exchange.WebServices.Data.ExchangeService -ArgumentList([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.Credentials = New-Object System.Net.NetworkCredential("", "password", "domain");

Now we are ready to use AutoDiscover. But depending on your infrastructure, AutoDiscover might need to follow some redirections before it has discovered your CAS Server. Like in this case:


Exception calling "AutodiscoverUrl" with "1" argument(s): "Autodiscover blocked a potentially insecure redirection to To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."
At line:1 char:25
+ $service.AutodiscoverUrl <<<< ("");
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

This happens because the AutoDiscover process looks at and instead of an A record pointing to the AutoDiscover service, it finds a CNAME redirecting it to Because this might pose a security risk, the AutoDiscoverUrl method aborts  the discovery process and throws the Exception displayed above. The solution is also outlined: Instead of calling the method AutoDiscoverUrl(mailAddress) call the overload which expects a delegate as a second paramter. This delegate has a string as input and returns the $true if the discovery process should follow the redirection; false otherwise.

How can this overload be used with PowerShell? The answer is a ScriptBlock. If you simply want to allow the discovery process to follow all redirects, simply call it this way:

$service.AutodiscoverUrl("", {$true})

But if you want to verify the discovery process is redirected to the correct url, use this version:

$TestUrlCallback = {
 param ([string] $url)
 if ($url -eq "") {$true} else {$false}

$service.AutodiscoverUrl("", $TestUrlCallback)

You can embed whatever checks you need to verify the given url in the third line of the $TestUrlCallback method.

Posted by Henning Krause on Friday, July 22, 2011 5:30 PM, last modified on Sunday, July 24, 2011 1:22 AM
Permalink | Post RSSRSS comment feed

Replying with attachments to an email message with EWS

The EWS Managed API makes some tasks really easy – like replying to an existing email. Given the unique id of an item, this can be done this way:

var message = (EmailMessage) Item.Bind(service, new ItemId(uniqueId), PropertySet.FirstClassProperties);
var reply = message.CreateReply(false);
reply.BodyPrefix = "Response text goes here";

But what if you want to send an attachment along with the reply? This is tricky, because the the instance created by the EmailMessage.CreateReply() method is of type ResponseMessage. Since its not an EmailMessage instance, it does not have an Attachment property. To add an attachment to this reply, it needs to be saved first. The Save method returns an EmailMessage instance. Attachments can be added to this message. Finally, the message can be sent to its destination.

var message = (EmailMessage) Item.Bind(service, new ItemId(uniqueId), PropertySet.FirstClassProperties);
var reply = message.CreateReply(false);
reply.BodyPrefix = "Response text goes here";
var replyMessage = reply.Save(WellKnownFolderName.Drafts);

Posted by Henning Krause on Monday, July 18, 2011 8:04 PM, last modified on Monday, July 18, 2011 8:04 PM
Permalink | Post RSSRSS comment feed

Using Streaming Notifications with Exchange 2010

That is the title of an article I wrote for Microsoft. It has been published here a few days ago:

Summary: Streaming notifications, which combine the functionalities of push and pull notifications, are new in Microsoft Exchange Server 2010 Service Pack 1 (SP1). This article explains how streaming notifications work and when to use them.

The code sample is missing, but that will be fixed in a few days.

Posted by Henning Krause on Friday, July 15, 2011 7:50 PM, last modified on Saturday, July 30, 2011 10:38 PM
Permalink | Post RSSRSS comment feed

Correlating a Non-Delivery-Notification to its original message with the Exchange Managed API

If you are automatically process emails in an Exchange Mailbox, you might also need to process non delivery reports (NDRs) and correlate these NDRs to their original values. Luckily, Exchange does most of the heavy lifting, as long as the NDR conforms to the RFC 3461, which defines the proper structure for an NDR that can be automatically parsed. Not all MTAs (Mail transfer agents) do generate these types of NDRs.

First of all, you need to check whether the mail item in question is actually a non delivery report. This is done by examining the Item Class of the mail. An NDR has an item class of REPORT.IPM.Note.NDR. Next, you need to retrieve the property PidTagParentKey from the item. This property contains the PidTagSearchKey of the original mail.

Unfortunately, the PidTagSearchKey cannot be used to bind to the item directly. Instead, you have to issue a FindItem operation to get it. Normally, sent items are all stored in the SentItems folder, so this narrows the search down.

Here is a sample method which describes the process:


   1:  class Program
   2:  {
   3:      private static readonly ExtendedPropertyDefinition PidTagParentKeyProperty = new ExtendedPropertyDefinition(0x25, MapiPropertyType.Binary);
   4:      private static readonly ExtendedPropertyDefinition PidTagSeachKeyProperty = new ExtendedPropertyDefinition(0x300B, MapiPropertyType.Binary);
   7:      private static bool TryGetOriginalMail(string ndrId, ExchangeService service, out Item originalItem)
   8:      {
   9:          byte[] value;
  11:          var item = service.BindToItems(new[] {new ItemId(ndrId)},
  12:                                          new PropertySet(BasePropertySet.IdOnly,
  13:                                                          PidTagParentKeyProperty, ItemSchema.Subject)).First().Item;
  15:          if (!item.TryGetProperty(PidTagParentKeyProperty, out value))
  16:          {
  17:              Console.Out.WriteLine("Correlationtoken not found.");
  18:              originalItem = null;
  19:              return false;
  20:          }
  22:          originalItem = service
  23:              .FindItems(WellKnownFolderName.SentItems,
  24:                          new SearchFilter.IsEqualTo(PidTagSeachKeyProperty, Convert.ToBase64String(value)),
  25:                          new ItemView(1) {PropertySet = PropertySet.FirstClassProperties})
  26:              .FirstOrDefault();
  28:          return true;
  29:      }
  30:  }

Posted by Henning Krause on Monday, June 27, 2011 8:12 PM, last modified on Monday, June 27, 2011 8:12 PM
Permalink | Post RSSRSS comment feed