List, Manage, and Backup Exchange Server Folders using EWS
List All Folders from Server
Aspose.Email API provides the capability to connect to the Exchange Server and list all the folders and sub-folders. You can also retrieve all the sub-folders from each folder recursively. It also provides the capability to enumerate folders with paging from the Exchange client using Exchange Web Serice (EWS). This article shows how to retrieve all the sub-folders from the Exchange server and retrieve folders with pagination.
The following code snippet shows you how to List folders from Exchange Server.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
public static void Run() | |
{ | |
try | |
{ | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
Console.WriteLine("Downloading all messages from Inbox...."); | |
ExchangeMailboxInfo mailboxInfo = client.GetMailboxInfo(); | |
Console.WriteLine("Mailbox URI: " + mailboxInfo.MailboxUri); | |
string rootUri = client.GetMailboxInfo().RootUri; | |
// List all the folders from Exchange server | |
ExchangeFolderInfoCollection folderInfoCollection = client.ListSubFolders(rootUri); | |
foreach (ExchangeFolderInfo folderInfo in folderInfoCollection) | |
{ | |
// Call the recursive method to read messages and get sub-folders | |
ListSubFolders(client, folderInfo); | |
} | |
Console.WriteLine("All messages downloaded."); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
private static void ListSubFolders(IEWSClient client, ExchangeFolderInfo folderInfo) | |
{ | |
// Create the folder in disk (same name as on IMAP server) | |
Console.WriteLine(folderInfo.DisplayName); | |
try | |
{ | |
// If this folder has sub-folders, call this method recursively to get messages | |
ExchangeFolderInfoCollection folderInfoCollection = client.ListSubFolders(folderInfo.Uri); | |
foreach (ExchangeFolderInfo subfolderInfo in folderInfoCollection) | |
{ | |
ListSubFolders(client, subfolderInfo); | |
} | |
} | |
catch (Exception) | |
{ | |
} | |
} |
Retrieve Folder Type Information
The FolderType property provided by ExchangeFolderInfo class can be used to get information about the type of the folder. It is shown in the code sample below.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
const string mailboxUri = "https://exchange/ews/exchange.asmx"; | |
const string domain = @""; | |
const string username = @"username@ASE305.onmicrosoft.com"; | |
const string password = @"password"; | |
NetworkCredential credentials = new NetworkCredential(username, password, domain); | |
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credentials); | |
ExchangeFolderInfoCollection folderInfoCol = client.ListSubFolders(client.MailboxInfo.RootUri); | |
foreach (ExchangeFolderInfo folderInfo in folderInfoCol) | |
{ | |
switch (folderInfo.FolderType) | |
{ | |
case ExchangeFolderType.Appointment: | |
// handle Appointment | |
break; | |
case ExchangeFolderType.Contact: | |
// handle Contact | |
break; | |
case ExchangeFolderType.Task: | |
// handle Task | |
break; | |
case ExchangeFolderType.Note: | |
// handle email message | |
break; | |
case ExchangeFolderType.StickyNote: | |
// handle StickyNote | |
break; | |
case ExchangeFolderType.Journal: | |
// handle Journal | |
break; | |
default: | |
break; | |
} |
Enumerate Folders with Paging Support
The following code snippet shows you how to use paging support using EWS.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Create instance of ExchangeWebServiceClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "UserName", "Password"); | |
// Call ListMessages method to list messages info from Inbox | |
ExchangeMessageInfoCollection msgCollection = client.ListMessages(client.GetMailboxInfo().InboxUri); | |
int itemsPerPage = 5; | |
List<PageInfo> pages = new List<PageInfo>(); | |
PageInfo pagedMessageInfoCol = client.ListMessagesByPage(client.MailboxInfo.InboxUri, itemsPerPage); | |
pages.Add(pagedMessageInfoCol); | |
while (!pagedMessageInfoCol.LastPage) | |
{ | |
pagedMessageInfoCol = client.ListMessagesByPage(client.MailboxInfo.InboxUri, itemsPerPage); | |
pages.Add(pagedMessageInfoCol); | |
} | |
pagedMessageInfoCol = client.ListMessagesByPage(client.MailboxInfo.InboxUri, itemsPerPage); | |
while (!pagedMessageInfoCol.LastPage) | |
{ | |
client.ListMessages(client.MailboxInfo.InboxUri); | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.Write(ex.Message); | |
} | |
finally | |
{ | |
} |
Access Custom Folders/Subfolders
IEWSClient lets developers access any custom folder or subfolder from the mailbox. The FolderExists() function of IEWSClient returns the URI of a specified custom folder/sub-folder, which can be used then to access the target folder. 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, make the following steps:
- Initialize the IEWSClient object by providing valid credentials.
- Access the default mailbox.
- Access the parent folder, which is INBOX in this example. This parent folder can also be a custom folder itself.
- Use FolderExists() to search the specified custom subfolder, for example “TestInbox”. It will return the URI of “TestInbox”.
- Use this Uri to access all the messages in that custom folder.
The following code snippet shows you how to access mailbox custom folders or subfolders with EWS.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Create instance of EWSClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
// Create ExchangeMailboxInfo, ExchangeMessageInfoCollection instance | |
ExchangeMailboxInfo mailbox = client.GetMailboxInfo(); | |
ExchangeMessageInfoCollection messages = null; | |
ExchangeFolderInfo subfolderInfo = new ExchangeFolderInfo(); | |
// Check if specified custom folder exisits and Get all the messages info from the target Uri | |
client.FolderExists(mailbox.InboxUri, "TestInbox", out subfolderInfo); | |
//if custom folder exists | |
if (subfolderInfo != null) | |
{ | |
messages = client.ListMessages(subfolderInfo.Uri); | |
// Parse all the messages info collection | |
foreach (ExchangeMessageInfo info in messages) | |
{ | |
string strMessageURI = info.UniqueUri; | |
// now get the message details using FetchMessage() | |
MailMessage msg = client.FetchMessage(strMessageURI); | |
Console.WriteLine("Subject: " + msg.Subject); | |
} | |
} | |
else | |
{ | |
Console.WriteLine("No folder with this name found."); | |
} |
List Public Folders
Microsoft Exchange Server lets users create public folders and post messages in them. To do this through your application, use Aspose.Email EWSClient class to connect to the Exchange Server and read and download messages and posts from public folders. The following code snippet shows you how to read all public folders, and subfolders, and list and download any messages found in these folders. This example only works with Microsoft Exchange Server 2007 or above since only these support EWS.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
public static string dataDir = RunExamples.GetDataDir_Exchange(); | |
public static string mailboxUri = "https://exchange/ews/exchange.asmx"; // EWS | |
public static string username = "administrator"; | |
public static string password = "pwd"; | |
public static string domain = "ex2013.local"; | |
public static void Run() | |
{ | |
try | |
{ | |
ReadPublicFolders(); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} | |
private static void ReadPublicFolders() | |
{ | |
NetworkCredential credential = new NetworkCredential(username, password, domain); | |
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential); | |
ExchangeFolderInfoCollection folders = client.ListPublicFolders(); | |
foreach (ExchangeFolderInfo publicFolder in folders) | |
{ | |
Console.WriteLine("Name: " + publicFolder.DisplayName); | |
Console.WriteLine("Subfolders count: " + publicFolder.ChildFolderCount); | |
ListMessagesFromSubFolder(publicFolder, client); | |
} | |
} | |
private static void ListMessagesFromSubFolder(ExchangeFolderInfo publicFolder, IEWSClient client) | |
{ | |
Console.WriteLine("Folder Name: " + publicFolder.DisplayName); | |
ExchangeMessageInfoCollection msgInfoCollection = client.ListMessagesFromPublicFolder(publicFolder); | |
foreach (ExchangeMessageInfo messageInfo in msgInfoCollection) | |
{ | |
MailMessage msg = client.FetchMessage(messageInfo.UniqueUri); | |
Console.WriteLine(msg.Subject); | |
msg.Save(dataDir + msg.Subject + ".msg", SaveOptions.DefaultMsgUnicode); | |
} | |
// Call this method recursively for any subfolders | |
if (publicFolder.ChildFolderCount > 0) | |
{ | |
ExchangeFolderInfoCollection subfolders = client.ListSubFolders(publicFolder); | |
foreach (ExchangeFolderInfo subfolder in subfolders) | |
{ | |
ListMessagesFromSubFolder(subfolder, client); | |
} | |
} | |
} |
Copy Messages to Another Folder
Aspose.Email API allows copying a message from one folder to another folder using the CopyItem method. The overloaded version of this method returns the Unique URI of the copied message as shown in this article.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
try | |
{ | |
// Create instance of EWSClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
MailMessage message = new MailMessage("from@domain.com", "to@domain.com", "EMAILNET-34997 - " + Guid.NewGuid().ToString(), "EMAILNET-34997 Exchange: Copy a message and get reference to the new Copy item"); | |
string messageUri = client.AppendMessage(message); | |
string newMessageUri = client.CopyItem(messageUri, client.MailboxInfo.DeletedItemsUri); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} |
Sync Folder Items
Aspose.Email for .NET API IEWSClient interface provides the feature of syncing an Exchange folder for its contents. The SyncFolder method exposed by the IEWSClient class can be used to perform folder sync information on a specified folder. The following code snippet shows you how to sync exchange folder information.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
MailMessage message1 = new MailMessage("user@domain.com", "user@domain.com", "EMAILNET-34738 - " + Guid.NewGuid().ToString(), "EMAILNET-34738 Sync Folder Items"); | |
client.Send(message1); | |
MailMessage message2 = new MailMessage("user@domain.com", "user@domain.com", "EMAILNET-34738 - " + Guid.NewGuid().ToString(),"EMAILNET-34738 Sync Folder Items"); | |
client.Send(message2); | |
ExchangeMessageInfoCollection messageInfoCol = client.ListMessages(client.MailboxInfo.InboxUri); | |
SyncFolderResult result = client.SyncFolder(client.MailboxInfo.InboxUri, null); | |
Console.WriteLine(result.NewItems.Count); | |
Console.WriteLine(result.ChangedItems.Count); | |
Console.WriteLine(result.ReadFlagChanged.Count); | |
Console.WriteLine(result.DeletedItems.Length); |
Retrieve Folder Permissions
Users are assigned permissions to public folders on Exchange Server, which limits/determines 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 PermissionLevel, whether they can CanCreateItems, DeleteItems, 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:
- Initialize the EWSClient.
- Use the ListPublicFolders to get a list of all public folders
- Retrieve the permissions associated with a folder using the GetFolderPermisssions() method
The following code snippet shows you how to use the EWSClient class to retrieve permissions applied to a folder.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string folderName = "DesiredFolderName"; | |
// Create instance of EWSClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
ExchangeFolderInfoCollection folders = client.ListPublicFolders(); | |
ExchangeFolderPermissionCollection permissions = new ExchangeFolderPermissionCollection(); | |
ExchangeFolderInfo publicFolder = null; | |
try | |
{ | |
foreach (ExchangeFolderInfo folderInfo in folders) | |
if (folderInfo.DisplayName.Equals(folderName)) | |
publicFolder = folderInfo; | |
if (publicFolder == null) | |
Console.WriteLine("public folder was not created in the root public folder"); | |
ExchangePermissionCollection folderPermissionCol = client.GetFolderPermissions(publicFolder.Uri); | |
foreach (ExchangeBasePermission perm in folderPermissionCol) | |
{ | |
ExchangeFolderPermission permission = perm as ExchangeFolderPermission; | |
if (permission == null) | |
Console.WriteLine("Permission is null."); | |
else | |
{ | |
Console.WriteLine("User's primary smtp address: {0}", permission.UserInfo.PrimarySmtpAddress); | |
Console.WriteLine("User can create Items: {0}", permission.CanCreateItems.ToString()); | |
Console.WriteLine("User can delete Items: {0}", permission.DeleteItems.ToString()); | |
Console.WriteLine("Is Folder Visible: {0}", permission.IsFolderVisible.ToString()); | |
Console.WriteLine("Is User owner of this folder: {0}", permission.IsFolderOwner.ToString()); | |
Console.WriteLine("User can read items: {0}", permission.ReadItems.ToString()); | |
} | |
} | |
ExchangeMailboxInfo mailboxInfo = client.GetMailboxInfo(); | |
//Get the Permissions for the Contacts and Calendar Folder | |
ExchangePermissionCollection contactsPermissionCol = client.GetFolderPermissions(mailboxInfo.ContactsUri); | |
ExchangePermissionCollection calendarPermissionCol = client.GetFolderPermissions(mailboxInfo.CalendarUri); | |
} | |
finally | |
{ | |
//Do the needfull | |
} |
Create and Manage Folders/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.
- Create an instance of IEWSClient.
- Set the 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.
- Use the CreateFolder method to create the folder.
The following code snippet shows you how to create folders and sub-Folders.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Create instance of EWSClient class by giving credentials | |
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"); | |
string inbox = client.MailboxInfo.InboxUri; | |
string folderName1 = "EMAILNET-35054"; | |
string subFolderName0 = "2015"; | |
string folderName2 = folderName1 + "/" + subFolderName0; | |
string folderName3 = folderName1 + " / 2015"; | |
ExchangeFolderInfo rootFolderInfo = null; | |
ExchangeFolderInfo folderInfo = null; | |
try | |
{ | |
client.UseSlashAsFolderSeparator = true; | |
client.CreateFolder(client.MailboxInfo.InboxUri, folderName1); | |
client.CreateFolder(client.MailboxInfo.InboxUri, folderName2); | |
} | |
finally | |
{ | |
if (client.FolderExists(inbox, folderName1, out rootFolderInfo)) | |
{ | |
if (client.FolderExists(inbox, folderName2, out folderInfo)) | |
client.DeleteFolder(folderInfo.Uri, true); | |
client.DeleteFolder(rootFolderInfo.Uri, true); | |
} | |
} |
Backup 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. This article describes taking backup of Exchange folders to a PST with sample code. In order to take the backup of Exchange server folders, the following steps may be followed.
- Initiate the IEWSClient with user credentials
- Add the required folder’s info to ExchangeFolderInfoCollection
- User the client’s Backup method to export the folder’s contents to PST
The following code snippet shows you how to backup exchange folders to PST.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string dataDir = RunExamples.GetDataDir_Exchange(); | |
// Create instance of IEWSClient class by providing credentials | |
const string mailboxUri = "https://ews.domain.com/ews/Exchange.asmx"; | |
const string domain = @""; | |
const string username = @"username"; | |
const string password = @"password"; | |
NetworkCredential credential = new NetworkCredential(username, password, domain); | |
IEWSClient client = EWSClient.GetEWSClient(mailboxUri, credential); | |
// Get Exchange mailbox info of other email account | |
ExchangeMailboxInfo mailboxInfo = client.GetMailboxInfo(); | |
ExchangeFolderInfo info = client.GetFolderInfo(mailboxInfo.InboxUri); | |
ExchangeFolderInfoCollection fc = new ExchangeFolderInfoCollection(); | |
fc.Add(info); | |
client.Backup(fc, dataDir + "Backup_out.pst", BackupOptions.None); |