Jens Willmer

Tutorials, projects, dissertations and more..

Work with Exchange Web Services

The following code has cost me allot of time. It was very hard to find the pieces and put them together. So I hope I can help a few of you with that post ;-)

The Problem

The problem was that I need to access different Exchange accounts via Exchange Web Services (EWS) and read out the mailbox size.


To do this I first used a view only account in the active directory that I have activated for impersonation by typing the following code into the Exchange-Shell:

| where {$_.IsClientAccessServer -eq $TRUE}
| ForEach-Object {Add-ADPermission -Identity $_.distinguishedname -User (Get-User -Identity User1 | select-object)
    .identity -extendedRight ms-Exch-EPI-Impersonation}

You can find an explanation to this code on MSDN.


Then I set up the connection string to the EWS:

// Certification Validation always true
ServicePointManager.ServerCertificateValidationCallback =
                        Object obj,
                        X509Certificate certificate,
                        X509Chain chain,
                        SslPolicyErrors errors)
                        return true;

// Setup connection string
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new NetworkCredential("viewadmin", "password", "FQDN");
service.AutodiscoverUrl("[email protected]");


Thirdly I used impersonation to connect to another mailbox account:

// Impersonate
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "[email protected]");


And finally I requested the folder size with this nice little piece of code:

private static readonly ExtendedPropertyDefinition PidTagMessageSizeExtended
                        = new ExtendedPropertyDefinition(0xe08, MapiPropertyType.Long);

/// <summary>
/// Gets the size of the mailbox in kilobytes.
/// </summary>
/// <param name="service">The ExchangeService object.</param>
/// <returns>Returns the used kilobytes in double.</returns>
public static double GetMailboxSize(ExchangeService service)
    var offset = 0;
    const int pagesize = 12;
    long size = 0;

    FindFoldersResults folders;
        folders = service.FindFolders(WellKnownFolderName.MsgFolderRoot,
                                      new FolderView(pagesize, offset, OffsetBasePoint.Beginning)
                                          Traversal = FolderTraversal.Deep,
                                          PropertySet =
                                              new PropertySet(BasePropertySet.IdOnly, PidTagMessageSizeExtended,

        foreach (var folder in folders)
            long folderSize;
            if (folder.TryGetProperty(PidTagMessageSizeExtended, out folderSize))
                size += folderSize;
        offset += pagesize;
    } while (folders.MoreAvailable);

    return size;

I hope I could help you. If you have improvements on the code don´t hazle to comment ;-)