Working with Folders on Exchange Server

The IEWSClient class lists, creates, synchronizes and backs up the folders of an Exchange mailbox and of the public folders of the organization. A folder is described by an ExchangeFolderInfo object; the methods of the client identify it by its URI.

The samples in this article use these headers and namespaces:

#include <MailMessage.h>
#include <SaveOptions.h>
#include <MsgSaveOptions.h>
#include <Clients/PageInfo.h>
#include <Clients/Exchange/WebService/EWSClient/EWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/IEWSClient.h>
#include <Clients/Exchange/WebService/SyncFolderResult.h>
#include <Clients/Exchange/ExchangeMailboxInfo.h>
#include <Clients/Exchange/ExchangeMessageInfo.h>
#include <Clients/Exchange/ExchangeMessageInfoCollection.h>
#include <Clients/Exchange/ExchangeFolderInfo.h>
#include <Clients/Exchange/ExchangeFolderInfoCollection.h>
#include <Clients/Exchange/ExchangeFolderPageInfo.h>
#include <Clients/Exchange/ExchangeFolderType.h>
#include <Clients/Exchange/ExchangePermissionCollection.h>
#include <Clients/Exchange/ExchangeBasePermission.h>
#include <Clients/Exchange/ExchangeFolderPermission.h>
#include <Clients/Exchange/ExchangeFolderPermissionAction.h>
#include <Clients/Exchange/ExchangeFolderPermissionReadAccess.h>
#include <Clients/Exchange/ExchangeFolderUserInfo.h>
#include <Storage/Pst/BackupOptions.h>
#include <system/array.h>
#include <system/collections/dictionary.h>
#include <system/convert.h>
#include <system/object_ext.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Clients;
using namespace Aspose::Email::Clients::Exchange;
using namespace Aspose::Email::Clients::Exchange::WebService;

Listing all Folders from Server

ListSubFolders() returns the direct subfolders of a folder. Starting from the root folder of the mailbox, whose URI is returned by get_RootUri() of the mailbox information, and calling the method again for every subfolder lists the whole folder tree.

The helper function below prints a folder and, indented, its subfolders:

static void PrintFolderTree(SharedPtr<IEWSClient> client, SharedPtr<ExchangeFolderInfo> folderInfo, int32_t depth)
{
    Console::WriteLine(String(u' ', depth * 2) + folderInfo->get_DisplayName());
    for (SharedPtr<ExchangeFolderInfo> subfolderInfo : client->ListSubFolders(folderInfo->get_Uri()))
    {
        PrintFolderTree(client, subfolderInfo, depth + 1);
    }
}
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

try
{
    SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
    Console::WriteLine(u"Mailbox URI: " + mailboxInfo->get_MailboxUri());

    for (SharedPtr<ExchangeFolderInfo> folderInfo : client->ListSubFolders(mailboxInfo->get_RootUri()))
    {
        PrintFolderTree(client, folderInfo, 0);
    }
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Get Folder Type Information using EWS

ExchangeFolderInfo::get_FolderType() tells which kind of items a folder holds, as an ExchangeFolderType value: Appointment for calendars, Contact, Task, Note, StickyNote, Journal and so on.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

for (SharedPtr<ExchangeFolderInfo> folderInfo : client->ListSubFolders(client->get_MailboxInfo()->get_RootUri()))
{
    Console::WriteLine(folderInfo->get_DisplayName() + u": " + ObjectExt::ToString(folderInfo->get_FolderType()));

    if (folderInfo->get_FolderType() == ExchangeFolderType::Appointment)
    {
        Console::WriteLine(u"  this folder is a calendar");
    }
}

client->Dispose();

Enumerating Folders with Paging Support using EWS

A folder with many subfolders can be listed page by page with ListSubFoldersByPage(). Each call returns an ExchangeFolderPageInfo with the subfolders of one page; the next page is requested with the offset of the current page plus one, until get_LastPage() returns true.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

try
{
    const int32_t itemsPerPage = 5;
    String rootUri = client->get_MailboxInfo()->get_RootUri();

    SharedPtr<ExchangeFolderPageInfo> pageInfo = client->ListSubFoldersByPage(rootUri, itemsPerPage);
    while (true)
    {
        Console::WriteLine(u"Page " + Convert::ToString(pageInfo->get_PageOffset()) + u":");
        for (SharedPtr<ExchangeFolderInfo> folderInfo : pageInfo->get_Items())
        {
            Console::WriteLine(u"  " + folderInfo->get_DisplayName());
        }

        if (pageInfo->get_LastPage())
        {
            break;
        }
        pageInfo = client->ListSubFoldersByPage(rootUri, itemsPerPage, pageInfo->get_PageOffset() + 1);
    }
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Accessing Mailbox Custom Folders or Subfolders

IEWSClient lets developers access any custom folder or subfolder from the mailbox. The FolderExists() method of IEWSClient checks whether a folder with the given name exists under a parent folder and, through its third argument, returns the information about the folder, including its URI. In the following example, a custom folder named “TestInbox”, which is created under INBOX is accessed and all the messages are displayed from this custom folder. To perform this task, the following steps are performed:

  1. Initialize the IEWSClient object by providing valid credentials.
  2. Access the default mailbox.
  3. Access the parent folder, which is INBOX in this example. This parent folder can also be a custom folder itself.
  4. Use FolderExists() method to search the specified custom subfolder, for example, “TestInbox”.
  5. Use the URI of the folder to access all the messages in that custom folder.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();

SharedPtr<ExchangeFolderInfo> subfolderInfo;
if (client->FolderExists(mailboxInfo->get_InboxUri(), u"TestInbox", subfolderInfo))
{
    for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(subfolderInfo->get_Uri()))
    {
        SharedPtr<MailMessage> message = client->FetchMessage(messageInfo->get_UniqueUri());
        Console::WriteLine(u"Subject: " + message->get_Subject());
    }
}
else
{
    Console::WriteLine(u"No folder with this name found.");
}

client->Dispose();

Listing Public Folders

Microsoft Exchange Server lets users create public folders and post messages in them. ListPublicFolders() returns the top-level public folders; ListSubFolders() and ListMessagesFromPublicFolder() give the subfolders and the messages of a public folder. The following code snippet reads all public folders and subfolders and saves the messages found in them as MSG files. This example only works with Microsoft Exchange Server 2007 or above since only these support EWS.

The helper function processes one folder and calls itself for the subfolders:

static void SaveMessagesFromPublicFolder(SharedPtr<IEWSClient> client, SharedPtr<ExchangeFolderInfo> folder, int32_t& count)
{
    Console::WriteLine(u"Folder Name: " + folder->get_DisplayName());
    for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessagesFromPublicFolder(folder))
    {
        SharedPtr<MailMessage> message = client->FetchMessage(messageInfo->get_UniqueUri());
        Console::WriteLine(message->get_Subject());
        message->Save(Convert::ToString(count++) + u"_public.msg", SaveOptions::get_DefaultMsgUnicode());
    }

    // Process the subfolders recursively
    if (folder->get_ChildFolderCount() > 0)
    {
        for (SharedPtr<ExchangeFolderInfo> subfolder : client->ListSubFolders(folder))
        {
            SaveMessagesFromPublicFolder(client, subfolder, count);
        }
    }
}
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

try
{
    int32_t count = 0;
    for (SharedPtr<ExchangeFolderInfo> publicFolder : client->ListPublicFolders())
    {
        Console::WriteLine(u"Name: " + publicFolder->get_DisplayName());
        Console::WriteLine(u"Subfolders count: " + Convert::ToString(publicFolder->get_ChildFolderCount()));
        SaveMessagesFromPublicFolder(client, publicFolder, count);
    }
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Synching Folder Items

SyncFolder() reports the changes of the items in a folder: new and changed items, items whose read flag changed and deleted items, in a SyncFolderResult. The first call, without a synchronization state, returns all items of the folder as new. The result also carries the state of the synchronization, get_SyncObject(); passing it to the next call returns only the changes made since then.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

SharedPtr<SyncFolderResult> result = client->SyncFolder(client->get_MailboxInfo()->get_InboxUri());
Console::WriteLine(u"Items in the folder: " + Convert::ToString(result->get_NewItems()->get_Count()));

client->Send(MakeObject<MailMessage>(u"user@domain.com", u"user@domain.com", u"Sync test", u"A new message"));

result = client->SyncFolder(result->get_SyncObject());
Console::WriteLine(u"New: " + Convert::ToString(result->get_NewItems()->get_Count()));
Console::WriteLine(u"Changed: " + Convert::ToString(result->get_ChangedItems()->get_Count()));
Console::WriteLine(u"Read flag changed: " + Convert::ToString(result->get_ReadFlagChanged()->get_Count()));
Console::WriteLine(u"Deleted: " + Convert::ToString(result->get_DeletedItems()->get_Length()));

client->Dispose();

Retrieving Permissions for Exchange Folders

Users are assigned permissions to public folders on Exchange Server, which determine the level of access a user has to these folders. The ExchangeFolderPermission class provides a set of permission properties for Exchange folders such as the permission level, whether the user can create items, delete items, and perform other tasks as specified by the permission properties. Permissions can be retrieved using the GetFolderPermissions() method of IEWSClient. This article shows how to retrieve the permissions applied to a public folder for all the users who have access to the shared folders.

To perform this task:

  1. Initialize the IEWSClient.
  2. Use the ListPublicFolders to get a list of all public folders
  3. Retrieve the permissions associated with a folder using the GetFolderPermissions() method

The same method returns the permissions of the folders of the mailbox, for example of the Contacts or the Calendar folder.

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

try
{
    SharedPtr<ExchangeFolderInfo> publicFolder;
    for (SharedPtr<ExchangeFolderInfo> folderInfo : client->ListPublicFolders())
    {
        if (folderInfo->get_DisplayName() == u"DesiredFolderName")
        {
            publicFolder = folderInfo;
        }
    }

    if (publicFolder == nullptr)
    {
        Console::WriteLine(u"The public folder was not found");
    }
    else
    {
        for (SharedPtr<ExchangeBasePermission> permission : client->GetFolderPermissions(publicFolder->get_Uri()))
        {
            Console::WriteLine(u"User's primary smtp address: " + permission->get_UserInfo()->get_PrimarySmtpAddress());
            Console::WriteLine(u"User can create items: " + Convert::ToString(permission->get_CanCreateItems()));
            Console::WriteLine(u"User can delete items: " + ObjectExt::ToString(permission->get_DeleteItems()));
            Console::WriteLine(u"Is folder visible: " + Convert::ToString(permission->get_IsFolderVisible()));
            Console::WriteLine(u"Is user owner of this folder: " + Convert::ToString(permission->get_IsFolderOwner()));

            SharedPtr<ExchangeFolderPermission> folderPermission = DynamicCast_noexcept<ExchangeFolderPermission>(permission);
            if (folderPermission != nullptr)
            {
                Console::WriteLine(u"User can read items: " + ObjectExt::ToString(folderPermission->get_ReadItems()));
            }
        }
    }

    // The permissions of the Contacts and the Calendar folders
    SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
    SharedPtr<ExchangePermissionCollection> contactsPermissions = client->GetFolderPermissions(mailboxInfo->get_ContactsUri());
    SharedPtr<ExchangePermissionCollection> calendarPermissions = client->GetFolderPermissions(mailboxInfo->get_CalendarUri());
    Console::WriteLine(u"Contacts: " + Convert::ToString(contactsPermissions->get_Count()) + u" permissions, Calendar: " + Convert::ToString(calendarPermissions->get_Count()) + u" permissions");
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();

Creating Folders and Sub-Folders

Aspose.Email API provides the capability to create folders in an Exchange mailbox. The CreateFolder method of IEWSClient can be used for this purpose. In order to create a folder in the Exchange server mailbox, the following steps can be used.

  1. Create an instance of IEWSClient.
  2. Set the set_UseSlashAsFolderSeparator property as required. If set to true, the application will consider the “Slash” as folder separator and the subfolder will be created after the slash.
  3. Use the CreateFolder method to create the folder.

The sample creates the folder “Projects” and its subfolder “2015” in the Inbox, finds both with FolderExists() and deletes them again with DeleteFolder().

SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

String inboxUri = client->get_MailboxInfo()->get_InboxUri();
String folderName = u"Projects";
String subfolderPath = folderName + u"/2015";

client->set_UseSlashAsFolderSeparator(true);
client->CreateFolder(inboxUri, folderName);
client->CreateFolder(inboxUri, subfolderPath);

SharedPtr<ExchangeFolderInfo> folderInfo;
SharedPtr<ExchangeFolderInfo> subfolderInfo;
if (client->FolderExists(inboxUri, folderName, folderInfo))
{
    if (client->FolderExists(inboxUri, subfolderPath, subfolderInfo))
    {
        client->DeleteFolder(subfolderInfo->get_Uri(), true);
    }
    client->DeleteFolder(folderInfo->get_Uri(), true);
}

client->Dispose();

Backup Exchange Folders to PST

It often so happens that users may want to take a backup of all or some of the mailbox folders. Aspose.Email provides the capability to take a backup of all or specified Exchange mailbox folders to a PST. In order to take a backup of Exchange server folders, the following steps may be followed.

  1. Create an instance of IEWSClient.
  2. Add the required folder’s info, read with GetFolderInfo(), to an ExchangeFolderInfoCollection.
  3. Use IEWSClient->Backup method to export the folder’s contents to PST. BackupOptions::Recursive also includes the subfolders.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");

SharedPtr<ExchangeFolderInfoCollection> folders = MakeObject<ExchangeFolderInfoCollection>();
folders->Add(client->GetFolderInfo(client->get_MailboxInfo()->get_InboxUri()));

try
{
    client->Backup(folders, u"Backup_out.pst", Storage::Pst::BackupOptions::None);
}
catch (System::Exception& ex)
{
    Console::WriteLine(ex->get_Message());
}

client->Dispose();