Ews Class |
Namespace: MailBee.EwsMail
The Ews type exposes the following members.
Name | Description | |
---|---|---|
Ews |
Creates an instance of Ews class.
| |
Ews(String) |
Creates and unlocks an instance of Ews class.
|
Name | Description | |
---|---|---|
AddAttachmentToItem |
Adds an attachment to an existing item.
| |
AddAttachmentToItemAsync |
Async/await version of AddAttachmentToItem(ItemId, String, String).
| |
Autodiscover |
Automatically determines the URL of the EWS server.
| |
CopyItem |
Copies the specified item (e.g. mail message) into the specified folder.
| |
CopyItemAsync |
Async/await version of CopyItem(ItemId, FolderId).
| |
CreateFolder |
Creates a folder in the MS Exchange account.
| |
CreateFolderAsync |
Async/await version of CreateFolder(String, FolderId).
| |
CreatePropSet |
Creates EWS Managed API PropertySet object.
| |
DeleteAttachment |
Deletes the attachment with the specified filename from the specified item.
| |
DeleteAttachmentAsync |
Async/await version of DeleteAttachment(ItemId, String, Boolean, Boolean).
| |
DeleteAttachments |
Deletes all attachments in the specified item.
| |
DeleteAttachmentsAsync |
Async/await version of DeleteAttachments(ItemId).
| |
DeleteFolder |
Deletes a folder with the specified ID.
| |
DeleteFolderAsync |
Async/await version of DeleteFolder(FolderId).
| |
DeleteItem |
Deletes the specified item (e.g. mail message).
| |
DeleteItemAsync |
Async/await version of DeleteItem(ItemId).
| |
DeleteItems |
Deletes the specified item (e.g. mail message).
| |
DeleteItemsAsync |
Async/await version of DeleteItems(IEnumerableItemId).
| |
Dispose |
Closes all opened network connections (if any) and releases any used system resources.
| |
Dispose(Boolean) |
When overridden in a derived class, must release unmanaged and optionally managed
resources used by the component.
| |
DownloadEntireMessage |
Downloads the specified item by its ID and returns it as MailMessage object.
| |
DownloadEntireMessageAsync |
Async/await version of DownloadEntireMessage(ItemId).
| |
DownloadFolderByFullName(String) |
Gets the reference to the folder denoted by its full name in the MS Exchange account.
| |
DownloadFolderByFullName(FolderId, String) |
Gets the reference to the given folder in the specified containing folder in the MS Exchange account.
| |
DownloadFolderByFullName(String, Int32) |
Gets the reference to the folder denoted by its full name in the MS Exchange account.
| |
DownloadFolderByFullNameAsync(String) |
Async/await version of DownloadFolderByFullName(String).
| |
DownloadFolderByFullNameAsync(FolderId, String) |
Async/await version of DownloadFolderByFullName(FolderId, String).
| |
DownloadFolderByFullNameAsync(String, Int32) |
Async/await version of DownloadFolderByFullName(String, Int32).
| |
DownloadFolderById(FolderId) |
Gets the reference to the folder with given ID in the MS Exchange account.
| |
DownloadFolderById(FolderId, PropertySet) |
Gets the reference to the folder with given ID in the MS Exchange account, also requesting the specified properties.
| |
DownloadFolderByIdAsync(FolderId) |
Async/await version of DownloadFolderById(FolderId).
| |
DownloadFolderByIdAsync(FolderId, PropertySet) |
Async/await version of DownloadFolderById(FolderId, PropertySet).
| |
DownloadFolderByShortName |
Gets the reference to the given folder in the MS Exchange account.
| |
DownloadFolderByShortNameAsync |
Async/await version of DownloadFolderByShortName(FolderId, String).
| |
DownloadFolders(Boolean) |
Downloads the list of folders of the MS Exchange account.
| |
DownloadFolders(FolderId, Boolean, Boolean) |
Downloads the list of folders of the MS Exchange account.
| |
DownloadFolders(FolderId, FolderView, SearchFilter, Boolean) |
Downloads the list of folders of the MS Exchange account.
| |
DownloadFoldersAsync(Boolean) |
Async/await version of DownloadFolders(Boolean).
| |
DownloadFoldersAsync(FolderId, Boolean, Boolean) |
Async/await version of DownloadFolders(FolderId, Boolean, Boolean).
| |
DownloadFoldersAsync(FolderId, FolderView, SearchFilter, Boolean) |
Async/await version of DownloadFolders(FolderId, FolderView, SearchFilter, Boolean).
| |
DownloadItem(FolderId, Int32) |
Downloads an item in the specified folder at the specified index.
| |
DownloadItem(ItemId, EwsItemParts) |
Downloads the specified portions of the specified item by its ID.
| |
DownloadItem(ItemId, PropertySet) |
Downloads the specified item by its ID using PropertySet settings.
| |
DownloadItem(FolderId, Int32, EwsItemParts) |
Downloads the specified portions of an Exchange item in the specified folder at the specified index.
| |
DownloadItem(FolderId, Int32, PropertySet) |
Downloads an item in the specified folder at the specified index using PropertySet settings.
| |
DownloadItemAsync(FolderId, Int32) |
Async/await version of DownloadItem(FolderId, Int32).
| |
DownloadItemAsync(ItemId, EwsItemParts) |
Async/await version of DownloadItem(ItemId, EwsItemParts).
| |
DownloadItemAsync(ItemId, PropertySet) |
Async/await version of DownloadItem(ItemId, PropertySet).
| |
DownloadItemAsync(FolderId, Int32, EwsItemParts) |
Async/await version of DownloadItem(FolderId, Int32, EwsItemParts).
| |
DownloadItemAsync(FolderId, Int32, PropertySet) |
Async/await version of DownloadItem(FolderId, Int32, PropertySet).
| |
DownloadItemIds(FolderId, Boolean) |
Downloads IDs of all or unread items in the specified folder.
| |
DownloadItemIds(FolderId, ItemView, Boolean) |
Downloads IDs of items in the specified folder in the specified ItemView range.
| |
DownloadItemIdsAsync(FolderId, Boolean) |
Async/await version of DownloadItemIds(FolderId, Boolean).
| |
DownloadItemIdsAsync(FolderId, ItemView, Boolean) |
Async/await version of DownloadItemIds(FolderId, ItemView, Boolean).
| |
DownloadItems(FolderId, Boolean) |
Downloads all or unread items in the specified folder.
| |
DownloadItems(IEnumerableEwsItem, EwsItemParts) |
Downloads the specified portions of the specified items.
| |
DownloadItems(IEnumerableEwsItem, PropertySet) |
Downloads the specified items using PropertySet settings.
| |
DownloadItems(FolderId, ItemView, Boolean) |
Downloads items in the specified folder in the specified ItemView range.
| |
DownloadItems(FolderId, ItemView, Boolean, EwsItemParts) |
Downloads the specified portions of the items in the specified ItemView range in the specified folder.
| |
DownloadItems(FolderId, ItemView, Boolean, PropertySet) |
Downloads items in the specified folder in the specified ItemView range using PropertySet settings.
| |
DownloadItems(FolderId, Int32, Int32, Boolean) |
Downloads items in the specified folder in the specified range.
| |
DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts) |
Downloads the specified portions of Exchange items in the specified folder in the specified range.
| |
DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet) |
Downloads items in the specified folder in the specified range using PropertySet settings.
| |
DownloadItemsAsync(FolderId, Boolean) |
Async/await version of DownloadItems(FolderId, Boolean).
| |
DownloadItemsAsync(IEnumerableEwsItem, EwsItemParts) |
Async/await version of DownloadItems(IEnumerableEwsItem, EwsItemParts).
| |
DownloadItemsAsync(IEnumerableEwsItem, PropertySet) |
Async/await version of DownloadItems(IEnumerableEwsItem, PropertySet).
| |
DownloadItemsAsync(FolderId, ItemView, Boolean) |
Async/await version of DownloadItems(FolderId, ItemView, Boolean).
| |
DownloadItemsAsync(FolderId, ItemView, Boolean, EwsItemParts) |
Async/await version of DownloadItems(FolderId, ItemView, Boolean, EwsItemParts).
| |
DownloadItemsAsync(FolderId, ItemView, Boolean, PropertySet) |
Async/await version of DownloadItems(FolderId, ItemView, Boolean, PropertySet).
| |
DownloadItemsAsync(FolderId, Int32, Int32, Boolean) |
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean).
| |
DownloadItemsAsync(FolderId, Int32, Int32, Boolean, EwsItemParts) |
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, EwsItemParts).
| |
DownloadItemsAsync(FolderId, Int32, Int32, Boolean, PropertySet) |
Async/await version of DownloadItems(FolderId, Int32, Int32, Boolean, PropertySet).
| |
DownloadNativeAttachments |
Downloads attachments with the specified string IDs.
| |
DownloadNativeAttachmentsAsync |
Async/await version of DownloadNativeAttachments(String, Boolean).
| |
EmptyFolder |
Empties a folder with the specified ID.
| |
EmptyFolderAsync |
Async/await version of EmptyFolder(FolderId, Boolean).
| |
Equals | Determines whether the specified object is equal to the current object. (Inherited from Object.) | |
EwsItemsToItemIds | ||
Finalize | Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.) | |
FindFolderIdByFullName(String) |
Gets the ID of the folder denoted by its full name in the MS Exchange account.
| |
FindFolderIdByFullName(FolderId, String) |
Gets the ID of the given folder in the specified containing folder in the MS Exchange account.
| |
FindFolderIdByFullName(String, Int32) |
Gets the ID of the given folder in the MS Exchange account.
| |
FindFolderIdByFullNameAsync(String) |
Async/await version of FindFolderIdByFullName(String).
| |
FindFolderIdByFullNameAsync(FolderId, String) |
Async/await version of FindFolderIdByFullName(FolderId, String).
| |
FindFolderIdByFullNameAsync(String, Int32) |
Async/await version of FindFolderIdByFullName(String, Int32).
| |
FindFolderIdByShortName |
Gets the ID of the given folder in the MS Exchange account.
| |
FindFolderIdByShortNameAsync |
Async/await version of FindFolderIdByShortName(FolderId, String).
| |
FolderExists(String) |
Checks if the folder with the specified full name exists in the MS Exchange account.
| |
FolderExists(FolderId, String) |
Checks if the given folder in the specified containing folder exists in the MS Exchange account.
| |
FolderExistsAsync(String) |
Async/await version of FolderExists(String).
| |
FolderExistsAsync(FolderId, String) |
Async/await version of FolderExists(FolderId, String).
| |
GetErrorDescription |
Returns a textual description of the last occurred error.
| |
GetExchangeVersionString |
Gets the MS Exchange version as a string.
| |
GetFolderByName |
Finds the EwsFolder in the given list by the folder's full name.
| |
GetFolderView |
Gets FolderView instance tuned for listing all the folders in the account.
| |
GetHashCode | Serves as the default hash function. (Inherited from Object.) | |
GetType | Gets the Type of the current instance. (Inherited from Object.) | |
InitEwsClient |
Sets the default MS Exchange version.
| |
InitEwsClient(ExchangeVersion) |
Sets the specific MS Exchange version.
| |
InitEwsClient(ExchangeVersion, TimeZoneInfo) |
Sets the specific MS Exchange version.
| |
MemberwiseClone | Creates a shallow copy of the current Object. (Inherited from Object.) | |
MoveFolder |
Moves a folder into another folder.
| |
MoveFolderAsync |
Async/await version of MoveFolder(FolderId, FolderId).
| |
MoveItem |
Moves the specified item (e.g. mail message) into the specified folder.
| |
MoveItemAsync |
Async/await version of MoveItem(ItemId, FolderId).
| |
OnErrorOccurred |
Used by MailBee to raise ErrorOccurred event.
| |
OnLogNewEntry |
Used by MailBee to raise LogNewEntry event.
| |
RenameFolder |
Renames a folder in the MS Exchange account.
| |
RenameFolderAsync |
Async/await version of RenameFolder(String, FolderId).
| |
RenameOrMoveFolder |
Renames or moves a folder denoted by its full name rather than by ID.
| |
RenameOrMoveFolderAsync |
Async/await version of RenameOrMoveFolder(String, String, ListEwsFolder).
| |
ResolveName |
Resolves the specified name into e-mail addresses which exist on the given MS Exchange server.
| |
ResolveNameAsync |
Async/await version of ResolveName(String).
| |
Search(FolderId, SearchFilter) |
Searches the specified folder for items matching the given criteria.
| |
Search(FolderId, SearchFilter, ItemView) |
Searches the specified folder for items matching the given criteria and delivers the results accordingly the specified ItemView.
| |
SearchAsync(FolderId, SearchFilter) |
Async/await version of Search(FolderId, SearchFilter).
| |
SearchAsync(FolderId, SearchFilter, ItemView) |
Async/await version of Search(FolderId, SearchFilter, ItemView).
| |
SendMessage |
Sends MailBee mail message.
| |
SendMessageAndSaveCopy |
Sends MailBee mail message and saves a copy in Sent Items or user-defined folder.
| |
SendMessageAndSaveCopyAsync |
Async/await version of SendMessageAndSaveCopy(MailMessage, FolderId).
| |
SendMessageAsync |
Async/await version of SendMessage(MailMessage).
| |
SetCredentials(ExchangeCredentials) |
Sets the credentials (e.g. OAuth2) of the MS Exchange account for subsequent operations.
| |
SetCredentials(String, String) |
Sets the login and password of the MS Exchange account for subsequent operations.
| |
SetServerUrl |
Gets or sets the URL of EWS service on MS Exchange server.
| |
TestConnection |
Makes a test connection to validate the current settings.
| |
TestConnectionAsync |
Async/await version of TestConnection.
| |
ToString | Returns a string that represents the current object. (Inherited from Object.) | |
UpdateItem |
Writes the changes made to the item to the MS Exchange server.
| |
UpdateItemAsync |
Async/await version of UpdateItem(EwsItem).
| |
UploadMessage(FolderId, MailMessage, Boolean) |
Uploads MailBee's MailMessage into the specified folder on the MS Exchange server.
| |
UploadMessage(FolderId, Byte, Boolean) |
Uploads raw message data into the specified folder on the MS Exchange server.
| |
UploadMessageAsync(FolderId, MailMessage, Boolean) |
Async/await version of UploadMessage(FolderId, MailMessage, Boolean).
| |
UploadMessageAsync(FolderId, Byte, Boolean) |
Async/await version of UploadMessage(FolderId, Byte, Boolean).
|
Name | Description | |
---|---|---|
CalculateFolderSizeOnDownload |
Gets or sets if folder download operation must also calculate the folder size in bytes.
| |
DefaultFolderClass |
Gets or sets the default class string to assign to folders being created.
| |
DeleteMethod |
Gets or sets the mode of deleting items in EWS.
| |
EnableCompatibilityMode |
Gets or sets if MailBee should work around bugs of Microsoft.Exchange.WebServices.dll library.
| |
EnableSslCertValidation |
Gets or sets if SSL certificate of the server must be validated (in case of HTTPS connection).
| |
FolderLevelDelimiter |
Gets or sets which character to use when delimiting nested folder names.
| |
LastResult |
Gets a numeric code of the last error.
| |
Log |
Gets the object used for logging MailBee activities into a file or memory buffer.
| |
MessageFoldersFilter |
Gets SearchFilter instance for reducing the list of the downloaded folders to mail-specific folders.
| |
RequireHttps |
Gets or sets if only HTTPS end points are allowed by auto-discover procedure.
| |
RootFolderType |
Gets or sets the top of folder hierarchy in an MS Exchange account.
| |
Service |
Gets a reference to the underlying ExchangeService object.
| |
Site |
Gets or sets the object to be used as a site for the component.
| |
ThrowExceptions |
Gets or sets whether the component will throw exceptions on errors.
| |
TrialDaysLeft |
Gets the number of days left to the date of the trial license key expiration.
| |
Version |
Gets the version of the MailBee assembly.
|
Name | Description | |
---|---|---|
Disposed |
Occurs after the component was disposed.
| |
ErrorOccurred |
Occurs when the MailBeeException is thrown.
| |
LogNewEntry |
This class is a wrapper for a subset of EWS Managed API library functions. This wrapper lets the developer work with EWS items in the way typical for other MailBee components (for instance, native exceptions of EWS Managed API are wrapped with MailBeeException, logging with Log property, etc). However, Ews class still exposes native EWS Managed API objects and types so you can utilize EWS Managed API for advanced tasks not directly covered by MailBee.
Note |
---|
In .NET Core, EWS is supported starting from .NET Core 2.0 (async methods only). In UWP, EWS requires Windows 10 Fall Creators Update as Min Target (async methods only). In .NET Framework, EWS is supported starting from .NET Framework v3.5 (sync methods only, not async). See more details in EWS Managed API topic. |
To use EWS, you need to add a reference to MailBee.NET.EWS.DLL (MailBee.NET.EWS package if you're using Nuget). In its turn, MailBee.NET.EWS.DLL references Managed EWS API (Microsoft.Exchange.WebServices.dll or Microsoft.Exchange.WebServices.NETStandard.dll in case of .NET Framework or .NET Core/UWP, respectively). The MailBee.NET.EWS package installs the dependent DLLs automatically.
The typical procedure of accessing EWS:
Note |
---|
In .NET Core or UWP, replace sync methods with their async versions. |
using System; using System.Collections.Generic; using System.Linq; using System.IO; using MailBee.EwsMail; using Microsoft.Exchange.WebServices.Data; // We need this because MailMessage type exists in both MailBee and Managed EWS. using MailBeeMailMessage = MailBee.Mime.MailMessage; using MailBeeAttachment = MailBee.Mime.Attachment; class Program { // We use this for displaying all strings but IDs. static string Shorten(string text, int maxLen) { if (text == null || text.Length <= maxLen) { return text; } else { return text.Substring(0, maxLen - 2) + ".."; } } // Because IDs usually have diff. endings but the same beginning, we'd better leave ending part. static string ShortenId(string text) { int maxLen = 10; if (text == null || text.Length <= maxLen) { return text; } else { return ".." + text.Substring((text.Length - maxLen) + 2); } } // Remove CRLFs from strings to make console outputs easier to read. static string Flatten(string text) { if (text == null) { return null; } else { return text.Replace("\r\n", " ").Replace('\n', ' '); } } static void Main(string[] args) { // If license key is not set in app.config or Registry, set it here. MailBee.Global.LicenseKey = "MN1XX-XXXXXXXX-XXXX"; // Enable self-signed server certificates. Remove this line to connect only to well-established servers with valid certificates. Ews.EnableSslCertValidation = false; Ews ewsClient = new Ews(); // Normally, use TimeZoneInfo.Local, or use TimeZoneInfo.Utc if getting "The specified time zone isn't valid" errors. ewsClient.InitEwsClient(ExchangeVersion.Exchange2010_SP1, TimeZoneInfo.Utc); // ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc); // If your Exchange server is newer or Office 365. // Log file can be used for debugging. You can also enable .NET Sockets own log by adding System.Net trace listener in app.config file (.NET Framework only). ewsClient.Log.Enabled = true; ewsClient.Log.Filename = @"C:\Temp\log.txt"; ewsClient.Log.Clear(); // Disabled Gzip results in more traffic (that's bad) but makes debugging easier ("network.log" file will contain human-readable data). ewsClient.Service.AcceptGzipEncoding = false; string email = "user@contoso.com"; // On-premise Exchange account // string email = "user@company.onmicrosoft.com"; // Microsoft account // Set on-premise Exchange server URL. ewsClient.SetServerUrl("http://domain/EWS/Exchange.asmx"); ewsClient.SetCredentials(email, "secret"); // Or set Office 365 server URL. // ewsClient.SetServerUrl("https://outlook.office365.com/EWS/Exchange.asmx"); // ewsClient.SetCredentials(email, "secret"); // Login/password auth // ewsClient.SetCredentials(oAuth2Creds); // Or OAuth2 creds, obtained separately (oAuth2Creds must be of ExchangeCredentials type) // Or use autodiscover (must be configured on the Exchange server, Office 365 server has autodiscover working). // ewsClient.Autodiscover(email); // ewsClient.RequireHttps = true; // ewsClient.SetCredentials(email, "secret"); // Send a mail message with attachment to myself. MailBeeMailMessage msg = new MailBeeMailMessage(); msg.Subject = "Test from EWS"; msg.BodyPlainText = "Test at " + DateTime.Now.ToString(); msg.BodyHtmlText = "<html>Test at " + DateTime.Now.ToString() + "</html>"; msg.Attachments.Add(@"C:\Temp\file.doc"); // Adjust this path to make it denote an existing file. msg.To.AddFromString("User <user@contoso.com>"); msg.From.AsString = "User <user@contoso.com>"; msg.SetUniqueMessageID(null); ewsClient.SendMessageAndSaveCopy(msg, null); // Also save copy to Sent Items. // ewsClient.SendMessage(msg); // Or just send. ewsClient.CalculateFolderSizeOnDownload = true; List<EwsFolder> folders = ewsClient.DownloadFolders(null, false, true); foreach (EwsFolder folder in folders) { Console.WriteLine(string.Format("Folder: '{0}', total msgs: {1}, unread: {2}, size in bytes: {3}", folder.ShortName, folder.TotalCount, folder.UnreadCount, folder.Size)); Console.WriteLine(folder.FullName); } // Get Sent Items folder from its well-known ID. EwsFolder sentFolder = ewsClient.DownloadFolderById(WellKnownFolderName.SentItems); Console.WriteLine(string.Format("You have {0} sent messages(s)", sentFolder.TotalCount)); EwsItemList sentItems = ewsClient.DownloadItems(sentFolder.Id, null, false, EwsItemParts.GenericItem); EwsItem lastSentItem = sentItems.FindLast(i => i.Subject == "Test from EWS"); if (lastSentItem != null) { // Demonstrate deleting messages. It's safe to delete this message because it's a test message we just sent. ewsClient.DeleteItem(lastSentItem.Id); Console.WriteLine("Deleted saved copy of a message we sent above"); } else { Console.WriteLine("For some reason, there was no saved copy of a message we sent above"); } // Will demonstrate various methods of getting EWS folder ID which then can then be used with many methods and properties. FolderId foldId = null; // Method 1: Get FolderId from folder name. foldId = ewsClient.FindFolderIdByFullName("Inbox"); // Method 2: Remember the fact we already have folder list downloaded, grab FolderId from there. // Note: this method is currently not working due to a bug in EWS Managed API. EwsFolder inbox = folders.Find(fold => (fold.Id.FolderName.HasValue && fold.Id.FolderName.Value == WellKnownFolderName.Inbox)); if (inbox == null) { // You'll most probably end up here. Console.WriteLine("Well-known folders only supported in Exchange 2013 and higher"); // You'll also need: // ewsClient.InitEwsClient(ExchangeVersion.Exchange2013_SP1, TimeZoneInfo.Utc); // ewsClient.EnableCompatibilityMode = false; // Update Microsoft.Exchange.WebServices.dll (current version v2.2 crashes when Well-known folder status if retrieved). // For the time being, fallback to searching by name. inbox = folders.Find(fold => (fold.FullName.ToUpper() == "INBOX")); } if (inbox == null) { Console.WriteLine("Couldn't find Inbox"); return; } else { foldId = inbox.Id; } // Method 3: Or simply get it via WellKnownFolderName directly. Easiest method. foldId = WellKnownFolderName.Inbox; Console.WriteLine("Download unread messages, body/headers"); // Default view means "return all items in the natural order". ItemView unreadView = null; // Or, modify the default view so that only 10 newest items are returned, newer first. int pageSize = 10; int page = 0; // We'll display items in pages. unreadView = new ItemView(pageSize, 0); unreadView.OrderBy.Add(EmailMessageSchema.DateTimeReceived, SortDirection.Descending); EwsItemList unreadItems = null; // Here we not using DownloadItems which accepts startIndex and count as we don't know in advance how many items we have. // Instead, we're relying on MoreAvailable property from EWS to determine if there are more items left. Console.WriteLine("Press Esc to skip downloading the next page of messages (if any)."); Console.WriteLine(); while (true) { unreadItems = ewsClient.DownloadItems(foldId, unreadView, false, EwsItemParts.GenericItem | EwsItemParts.MailMessageBody | EwsItemParts.MailMessageRecipients); if (unreadView != null) { Console.WriteLine(string.Format("Downloading up to {0} message(s) starting at offset {1} from total of {2}, {3} message(s) actually downloaded.", pageSize, unreadView.Offset, unreadItems.TotalCount, unreadItems.Count)); } foreach (EwsItem item in unreadItems) { Console.WriteLine(string.Format("UID: {0} Text: {1} HTML: {2}", ShortenId(item.UniqueId), Flatten(Shorten(item.BodyPlainText, 40)), Flatten(Shorten(item.BodyHtmlText, 40)))); Console.WriteLine(); } Console.WriteLine(); if (unreadItems.MoreAvailable) { if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) { Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples."); break; } else { Console.WriteLine("Will download the next page."); } } else { Console.WriteLine("The last page is done."); break; } unreadView.Offset = unreadItems.NextPageOffset; } Console.WriteLine(); Console.WriteLine("Download unread messages, full messages with attachments"); unreadItems = ewsClient.DownloadItems(unreadItems, EwsItemParts.MailMessageFull); for (int i = 0; i < unreadItems.Count; i++) { EwsItem item = unreadItems[i]; Console.WriteLine(string.Format("ID {0} size: {1}, attachments count: {2}, attachments: {3}", Shorten(item.UniqueId, 10), item.Size, item.MailBeeMessage.Attachments.Count, string.Join(", ", item.MailBeeMessage.Attachments.Cast<MailBeeAttachment>().Select(a => Shorten(a.Filename, 20))))); // For last message, do additional processing. if (i == unreadItems.Count - 1) { if (item.MailBeeMessage.Attachments.Count > 0) { // Save all attachments using MailBee. item.MailBeeMessage.Attachments.SaveAll(@"C:\Temp", true); // Save a particular attachment using MailBee. item.MailBeeMessage.Attachments[0].SaveToFolder(@"C:\Temp", true); } if (item.NativeMessage.Attachments.Count > 0) { // Demonstrate working with attachments directly via Managed EWS API. Console.WriteLine(" Attachment ID to name: " + string.Join(", ", item.NativeMessage.Attachments.Select(a => ShortenId(a.Id) + ": " + Shorten(a.Name, 20)))); IEnumerable<FileAttachment> fileAttachs = item.NativeMessage.Attachments.OfType<FileAttachment>(); if (fileAttachs.Count() > 0) { Console.WriteLine(" File attachment IDs: " + string.Join(", ", fileAttachs.Select(fa => ShortenId(fa.Id)))); FileAttachment fileAttach = fileAttachs.First(); fileAttach.Load(Path.Combine(@"C:\Temp", fileAttach.Name)); // This will save attachment to disk. } } // Add attachment to message and then delete it. This is a kind of action you can only do with EWS and not with POP3 or IMAP, for example // (you cannot alter existing messages in POP3/IMAP, only mark them with flags). Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count)); FileAttachment newAttach = ewsClient.AddAttachmentToItem(item.Id, @"C:\Temp\test.txt", "filename.txt"); item.NativeItem.Load(); Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count)); Console.WriteLine("Will delete attachment just added"); int countAttachsDeleted = ewsClient.DeleteAttachment(item.Id, newAttach.Id, true, true); item.NativeItem.Load(); Console.WriteLine(string.Format("Attachment ID: {0}, instances deleted: {1}", ShortenId(newAttach.Id), countAttachsDeleted)); Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count)); bool deleteOtherAttachs = false; // Set to true to enable deletion of other attachments. Do this only in test accounts, not in your normal account! if (deleteOtherAttachs) { Console.WriteLine("Will delete the remaining attachments, if any"); ewsClient.DeleteAttachments(item.Id); item.NativeItem.Load(); Console.WriteLine(string.Format("Attachment count: {0}", item.NativeMessage.Attachments.Count)); } } } Console.WriteLine(); // Update message flags to mark last message in the folder as unread (just to make sure the search for unread messages below will find at least one message). if (inbox.TotalCount > 0) { EwsItem item = ewsClient.DownloadItem(foldId, 0, EwsItemParts.IdOnly); item.IsRead = true; ewsClient.UpdateItem(item); } // Clear keyboard buffer to avoid earlier Esc strokes alter the code flow below. while (Console.KeyAvailable) { Console.ReadKey(); } Console.WriteLine("Search for unread messages via using SearchFilter"); SearchFilter filt = null; // "No filter" means "Search all messages". filt = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false); // Modify filter to allow only unread messages. unreadItems = ewsClient.Search(foldId, filt); string unreadUids = string.Join(", ", unreadItems.Select(it => ShortenId(it.UniqueId))); Console.WriteLine("Unread IDs (you can then pass them to DownloadItems): " + unreadUids); Console.WriteLine(); // Simply display all messages in the folder with paging. We know in advance how many items to display so we don't need MoreAvailable and custom ItemView. Console.WriteLine("Display all messages in the folder in paged manner"); Console.WriteLine("Press Esc to skip downloading the next page of messages (if any)."); Console.WriteLine(); EwsItemList items = null; while (page * pageSize < inbox.TotalCount) { // You can replace EwsItemParts.GenericItem with EwsItemParts.MailMessageFull to download full messages (with body/attachments) instead of basic info. // If you do this replacement, item.MailBeeMessage will no longer be null. items = ewsClient.DownloadItems(foldId, page * pageSize, pageSize, true, EwsItemParts.GenericItem); foreach (EwsItem item in items) { if (item.MailBeeMessage == null) { Console.WriteLine(string.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}", Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size)); } else { Console.WriteLine(string.Format("To: '{0}', From: '{1}', Subject: '{2}', IsRead: {3}, Size: {4}, MailBeeMessage.Size: {5}", Shorten(item.To, 20), Shorten(item.From, 20), Shorten(item.Subject, 20), item.IsRead, item.Size, item.MailBeeMessage.Size)); } } page++; Console.WriteLine("------------"); if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) { Console.WriteLine("Esc pressed, will skip downloading the remaining pages and proceed to other examples."); break; } } // Demonstrate working with deeply nested folders. EWS Managed API itself can only work with one level, MailBee adds this functionality on top of EWS. if (!ewsClient.FolderExists("Inbox/2nd level/3rd level")) { // Create a deeply nested folder. ewsClient.CreateFolder("Inbox/2nd level/3rd level", null); Console.WriteLine("Created folder \"Inbox/2nd level/3rd level\""); } } }