Rebex Secure Mail

SMTP, IMAP, EWS, POP3, S/MIME .NET library

Download 30-day free trial Buy from $299
More .NET libraries

Back to feature list...

EWS - message operations

The sample code on this page assumes you have already connected and authenticated to an Exchange server.

Getting list of messages 

To get a list of messages, use GetMessageList method. Following code shows how to get list top few messages in the Inbox.

// create EWS client instance
using (var client = new Rebex.Net.Ews())
{
    // connect and login
    client.Connect(hostname, SslMode.Implicit);
    client.Login(username, password);

    // get all message in the Inbox folder
    var list = client.GetMessageList(EwsFolderId.Inbox);

    foreach (var messageInfo in list)
    {
        Console.WriteLine(
            "From: {0} Subject: {1}",
            messageInfo.From,
            messageInfo.Subject);
    }

    // disconnect (not required, but polite)
    client.Disconnect();
}
' create IMAP client instance
Using client = New Rebex.Net.Ews()
    ' connect to Exchange   server
    client.Connect(hostname, SslMode.Implicit)

    ' authenticate
    client.Login(username, password)

    ' to select folder to work with use either
    '  - client.FindFolder(EwsFolderId.Root, "folderName")
    '  - predefined folder id
    Dim folder = EwsFolderId.Inbox

    ' get list of unread messages
    Dim list As EwsMessageCollection = client.Search(
        folder,
        EwsSearchParameter.IsRead(False))

    ' print some info
    For Each messageInfo As EwsMessageInfo In list
        Console.WriteLine("From: {0}", messageInfo.From)
        Console.WriteLine("To: {0}", messageInfo.To)
        Console.WriteLine("Subject: {0}", messageInfo.Subject)
    Next

    ' disconnect (not required, but polite)
    client.Disconnect()
End Using

Interested where does EwsFolderI.Inbox come from?

Tip: You can make things faster by choosing which message fields to return. Default includes basic properties such as From, Subject or ReceivedDate.

Getting list of messages with paging 

A folder can contain thousands of items. Retrieving all of them would consume whole transfer bandwidth and block your application for a very long time. Additionally, it's usually not even possible because Exchange server limits the maximum number of items and messages it can return in response to a single API call.

For many applications, working with several hundreds or thousands of latest items is entirely sufficient. When it isn't, use one of the two kinds of page views described in detail in Paging results section.

The following code shows how to retrieve a list of all messages in the 'Inbox' folder by calling GetMessageList multiple times folder using the paging functionality:

// create EWS client instance, connect, log in
// ...

// list all messages
int offset = 0;
int pageSize = 500;
while (true)
{
    // get items of next page
    EwsMessageCollection messages = ews.GetMessageList(
        EwsFolderId.Inbox, EwsPageView.CreateIndexed(offset, pageSize));

    // print info about items
    foreach (EwsMessageInfo message in messages)
    {
        Console.WriteLine("----- ----- -----");
        Console.WriteLine("From: {0}", message.From);
        Console.WriteLine("Subject: {0}", message.Subject);
        Console.WriteLine("Size: {0}kB", message.Size / 1024);
        if (message.HasAttachments)
            Console.WriteLine(" @ has attachments");
    }

    // break if this is the last page
    if (messages.PageResult.IsLastPage)
        break;

    // set next offset
    if (messages.PageResult.NextOffset.HasValue)
        offset = messages.PageResult.NextOffset.Value;
    else
        offset += pageSize;
}
' create EWS client instance, connect, log in
' ...

' list all messages
Dim offset As Integer = 0
Dim pageSize As Integer = 500
While True
    ' get items of next page
    Dim messages As EwsMessageCollection = ews.GetMessageList(
        EwsFolderId.Inbox, EwsPageView.CreateIndexed(offset, pageSize))

    ' print info about items
    For Each message As EwsMessageInfo In messages
        Console.WriteLine("----- ----- -----")
        Console.WriteLine("From: {0}", message.From)
        Console.WriteLine("Subject: {0}", message.Subject)
        Console.WriteLine("Size: {0}kB", message.Size / 1024)
        If message.HasAttachments Then
            Console.WriteLine(" @ has attachments")
        End If
    Next

    ' break if this is the last page
    If messages.PageResult.IsLastPage Then
        Exit While
    End If

    ' set next offset
    If messages.PageResult.NextOffset.HasValue Then
        offset = messages.PageResult.NextOffset.Value
    Else
        offset += pageSize
    End If
End While

Unfortunately, the GetMessageList method is not able to retrieve To and Body fields due to limitations of Exchange server. If you need this information, use GetMessageInfo to retrieve additional information. Alternatively, call GetMessageList with EwsItemFields.Id to only retrieve a list of message IDs, followed by calls to GetMessageInfo to retrieve desired information about each message:

// create EWS client instance, connect, log in
// ...

// get get some messages
EwsMessageCollection messages = ews.GetMessageList(
    EwsFolderId.Inbox, EwsItemFields.Id, EwsPageView.CreateIndexed(0, 25));

// print info about items
foreach (EwsMessageInfo temp in messages)
{
    EwsMessageInfo message = ews.GetMessageInfo(
        temp.Id, EwsItemFields.Info);

    Console.WriteLine("----- ----- -----");
    Console.WriteLine("From: {0}", message.From);
    Console.WriteLine("To: {0}", message.To);
    Console.WriteLine("Subject: {0}", message.Subject);
}
' create EWS client instance, connect, log in
' ...

' get get some messages
Dim messages As EwsMessageCollection = ews.GetMessageList(
    EwsFolderId.Inbox, EwsItemFields.Id, EwsPageView.CreateIndexed(0, 25))

' print info about items
For Each temp As EwsMessageInfo In messages
    Dim message As EwsMessageInfo = ews.GetMessageInfo(
        temp.Id, EwsItemFields.Info)

    Console.WriteLine("----- ----- -----")
    Console.WriteLine("From: {0}", message.From)
    Console.WriteLine("To: {0}", message.[To])
    Console.WriteLine("Subject: {0}", message.Subject)
Next

Note: GetMessageList method can handle non-message items as well (it returns placeholder objects).

Getting message info 

To get information about a message, use GetMessageInfo method.

By default, information specified by EwsItemFields.Default is retrieved. This includes basic properties such as From, Subject, ReceivedDate and Size.

// create EWS client instance, connect, log in
// ...

// get full info about message
EwsMessageInfo message = ews.GetMessageInfo(
    messageId, EwsItemFields.Full);

// print some info about the message
Console.WriteLine("From: {0}", message.From);
Console.WriteLine("To: {0}", message.To);
Console.WriteLine("Subject: {0}", message.Subject);
Console.WriteLine("Size: {0}kB", message.Size / 1024);
if (message.HasAttachments)
{
    Console.WriteLine("Attachments:");
    foreach (EwsAttachmentInfo item in message.Attachments)
    {
        Console.WriteLine(" {0} <{1}>", item.Name, item.ContentType);
    }
}
' create EWS client instance, connect, log in
' ...

' get full info about message
Dim message As EwsMessageInfo = ews.GetMessageInfo(messageId, EwsItemFields.Full)

' print some info about the message
Console.WriteLine("From: {0}", message.From)
Console.WriteLine("To: {0}", message.[To])
Console.WriteLine("Subject: {0}", message.Subject)
Console.WriteLine("Size: {0}kB", message.Size / 1024)
If message.HasAttachments Then
    Console.WriteLine("Attachments:")
    For Each item As EwsAttachmentInfo In message.Attachments
        Console.WriteLine(" {0} <{1}>", item.Name, item.ContentType)
    Next
End If

Tip: You can specify which fields to retrieve to improve the performance of your application.

Note: GetMessageInfo method can handle non-message items as well (it returns a placeholder object).

Downloading messages 

To download and parse a whole mail message into a MailMessage object (used by our IMAP, POP3 and SMTP objects as well), use GetMailMessage method:

// create EWS client instance, connect, log in
// ...

// get a message
MailMessage message = ews.GetMailMessage(messageId);

// print some info about the message
Console.WriteLine("From: {0}", message.From);
Console.WriteLine("To: {0}", message.To);
Console.WriteLine("Subject: {0}", message.Subject);
if (message.Attachments.Count > 0)
{
    Console.WriteLine("Attachments:");
    foreach (Attachment item in message.Attachments)
    {
        Console.WriteLine(" {0} <{1}>", item.DisplayName, item.ContentType);
    }
}
' create EWS client instance, connect, log in
' ...

' get a message
Dim message As MailMessage = ews.GetMailMessage(messageId)

' print some info about the message
Console.WriteLine("From: {0}", message.From)
Console.WriteLine("To: {0}", message.[To])
Console.WriteLine("Subject: {0}", message.Subject)
If message.Attachments.Count > 0 Then
    Console.WriteLine("Attachments:")
    For Each item As Attachment In message.Attachments
        Console.WriteLine(" {0} <{1}>", item.DisplayName, item.ContentType)
    Next
End If

This retrieves an instance of high-level MailMessage object. If you prefer the low-level API (MimeMessage object), call GetMimeMessage method instead.

Alternatively, you can easily download a message into a file using GetMessage method:

// create EWS client instance, connect, log in
// ...

// download a message to a file in MIME format
ews.GetMessage(messageId, @"C:\data\message.eml");
' create EWS client instance, connect, log in
' ...

' download a message to a file in MIME format
ews.GetMessage(messageId, "C:\data\message.eml")

To download the message into a Stream, use another GetMessage overload:

// create EWS client instance, connect, log in
// ...

using (Stream writer = File.Create(@"C:\data\message.eml"))
{
    // download a message to a stream in MIME format
    ews.GetMessage(messageId, writer);
}
' create EWS client instance, connect, log in
' ...

Using writer As Stream = File.Create("C:\data\message.eml")
    ' download a message to a stream in MIME format
    ews.GetMessage(messageId, writer)
End Using

To download the message as raw SOAP XML or in a native Exchange export format, use GetItem method instead:

// create EWS client instance, connect, log in
// ...

// download a message to a file in SOAP XML format
ews.GetItem(messageId, @"C:\data\message.xml", EwsItemFormat.Xml);

// download a message to a file in native Exchange export format
ews.GetItem(messageId, @"C:\data\message.raw", EwsItemFormat.Native);
' create EWS client instance, connect, log in
' ...

' download a message to a file in SOAP XML format
ews.GetItem(messageId, "C:\data\message.xml", EwsItemFormat.Xml)

' download a message to a file in native Exchange export format
ews.GetItem(messageId, "C:\data\message.raw", EwsItemFormat.Native)

Uploading messages 

You can even upload messages to an Exchange folder. The StoreMessage method accepts MailMessage or MimeMessage objects. To upload a mail from file or stream, load it to MailMessage object first:

// create EWS client instance, connect, log in
// ...

// load a mail message
MailMessage mail = new MailMessage();
mail.Load(@"C:\data\message.eml");

// upload the mail to 'Inbox' folder
EwsItemId messageId = ews.StoreMessage(EwsFolderId.Inbox, mail);

// (save its ID for later use if needed)
' create EWS client instance, connect, log in
' ...

' load a mail message
Dim mail As New MailMessage()
mail.Load("C:\data\message.eml")

' upload the mail to 'Inbox' folder
Dim messageId As EwsItemId = ews.StoreMessage(EwsFolderId.Inbox, mail)

' (save its ID for later use if needed)

Checking for message existence 

To check whether an item (or a message) exists, use ItemExists method.

Importing and exporting messages 

To transfer an item from one Exchange server to another, use ExportItem and ImportItem methods.

The ExportItem method retrieves data of an item in its native Exchange export format. The ImportItem method imports this data to an Exchange server and returns a new ID associated with the imported item (ID of the original item is not retained).

// create EWS clients, connect, log in
Ews ews1 = new Ews();
ews1.Connect(serverName1);
ews1.Login(username1, password1);

Ews ews2 = new Ews();
ews2.Connect(serverName2);
ews2.Login(username2, password2);

// export an item from server 1
byte[] raw = ews1.ExportItem(itemId1);

// import the item to server 2
EwsItemId itemId2 = ews2.ImportItem(EwsFolderId.Inbox, raw);
' create EWS clients, connect, log in
Dim ews1 As New Ews()
ews1.Connect(serverName1)
ews1.Login(username1, password1)

Dim ews2 As New Ews()
ews2.Connect(serverName2)
ews2.Login(username2, password2)

' export an item from server 1
Dim raw As Byte() = ews1.ExportItem(itemId1)

' import the item to server 2
Dim itemId2 As EwsItemId = ews2.ImportItem(EwsFolderId.Inbox, raw)
Note: ImportItem and ExportItem methods are available in Exchange 2010 SP1 and later.

Copying and moving messages 

To copy a message to a folder, use CopyItem method. To move a message to another folder, use MoveItem method.

// create EWS client instance, connect, log in
// ...

DateTime yesterday = DateTime.Now.Date.AddDays(-1);

// get 'Archive' folder
EwsFolderInfo archive = ews.FindFolder(EwsFolderId.Root, "Archive");
if (archive == null)
    throw new ApplicationException("Archive folder not found.");

// find all messages that arrived yesterday
EwsItemCollection items = ews.SearchItems(
    EwsFolderId.Inbox,
    EwsSearchParameter.Arrived(yesterday));

// process all found messages
foreach (EwsItemInfo item in items)
{
    // move or copy all messages from 'Inbox' to 'Archive' folder
    if (move)
        ews.MoveItem(item.Id, archive.Id);
    else
        ews.CopyItem(item.Id, archive.Id);
}
' create EWS client instance, connect, log in
' ...

Dim yesterday As DateTime = DateTime.Now.Date.AddDays(-1)

' get 'Archive' folder
Dim archive As EwsFolderInfo = ews.FindFolder(EwsFolderId.Root, "Archive")

If archive Is Nothing Then
    Throw New ApplicationException("Archive folder not found.")
End if

' find all messages which arrived yesterday
Dim items As EwsItemCollection = ews.SearchItems(
    EwsFolderId.Inbox,
    EwsSearchParameter.Arrived(yesterday))

' process all found messages
For Each item As EwsItemInfo In items
    ' move or copy all messages from 'Inbox' to 'Archive' folder
    If move Then
        ews.MoveItem(item.Id, archive.Id)
    Else
        ews.CopyItem(item.Id, archive.Id)
    End If
Next

Tip: Both CopyItem and MoveItem methods return the ID of the new item.

Deleting messages 

To delete a message, use DeleteItem method.

Note: Use DeleteMode property to specify whether delete message permanently or move it to Deleted Items folder.

// create EWS client instance, connect, log in
// ...

// delete an item
ews.DeleteItem(itemId);
' create EWS client instance, connect, log in
' ...

' delete an item
ews.DeleteItem(itemId)

Message metadata (importance, flags, categories and more) 

Exchange items feature lot of various properties. Some of them can be changed. To set a metadata or other property of an item or a message, use UpdateItem method.

The following writable properties are supported:

  • IsRead - determines whether the message was read already
  • Importance - importance of the message (high/normal/low)
  • Flag - flag status of the message (none/flagged/completed)
  • Categories - custom string categories of the message
  • Body - HTML or plain text body of the message

The following code shows how to update various properties of a message:

// create EWS client instance, connect, log in
// ...

// prepare metadata to be set
var meta = new EwsMessageMetadata();
meta.Importance = MailPriority.High;
meta.IsRead = false;
meta.Flag = new EwsFlag(EwsFlagStatus.Flagged);
// set two categories
meta.Categories = new string[] {"Green", "Orange"};

// update item metadata
ews.UpdateItem(messageId, meta);
' create EWS client instance, connect, log in
' ...

' prepare metadata to be set
Dim meta = New EwsMessageMetadata()
meta.Importance = EwsItemImportance.High
meta.IsRead = False
meta.Flag = New EwsFlag(EwsFlagStatus.Flagged)
' set two categories
meta.Categories = New String() {"Green", "Orange"}

' update item metadata
ews.UpdateItem(messageId, meta)

Message categories 

Exchange makes it possible to assign one or more categories to items and messages. Categories are associated with a color label, which makes it possible to visually distinguish important messages.

Categories can be managed at the Exchange server and some of them are usually predefined - this includes 'Red category', 'Green category' and so on.

From Ews object's point-of-view, a category is simply a string. If a category is known to the Exchange server, the item is shown with the color label. If a category is not known to the Exchange server, the item is shown without a color label.

The UpdateItem method makes it possible to set categories of an item or a message:

// prepare a list of categories to set
//  - Red category: one of Exchange default categories
//  - Joe: custom category (previously created at Exchange server)
//  - Due $DATE$: custom category unknown to Exchange server
var meta = new EwsItemMetadata();
meta.Categories = new EwsCategoryCollection();
meta.Categories.Add("Joe");
meta.Categories.Add("Red");
meta.Categories.Add("Due " + DateTime.Now.AddDays(1).ToShortDateString());

// update item metadata
ews.UpdateItem(itemId, meta);
' prepare a list of categories to set
'  - Red category: one of Exchange default categories
'  - Joe: custom category (previously created at Exchange server)
'  - Due $DATE$: custom category unknown to Exchange server
Dim meta = New EwsItemMetadata()
meta.Categories = New EwsCategoryCollection()
meta.Categories.Add("Joe")
meta.Categories.Add("Red category")
meta.Categories.Add("Due " + DateTime.Now.AddDays(1).ToShortDateString())

' update item metadata
ews.UpdateItem(itemId, meta)

Setting categories overwrites previous ones. Therefore, to add a category, retrieve the current category list first, add additional categories and call UpdateItem as usual:

// create EWS client instance, connect, log in
// ...

// get message info to retreive present categories
var info = ews.GetMessageInfo(itemId, EwsItemFields.Info);

// prepare metadata to add a category to an item
var meta = new EwsItemMetadata();

// initialize metadata categories with those from the message info
meta.Categories = new EwsCategoryCollection(info.Categories);

// add a category
meta.Categories.Add("Blue");

// update item metadata
ews.UpdateItem(itemId, meta);
' create EWS client instance, connect, log in
' ...

' get message info to retreive present categories
Dim info = ews.GetMessageInfo(itemId, EwsItemFields.Info)

' prepare metadata to add a category to an item
Dim meta = New EwsItemMetadata()

' initialize metadata categories with those from the message info
meta.Categories = New EwsCategoryCollection(info.Categories)

' add a category
meta.Categories.Add("Blue")

' update item metadata
ews.UpdateItem(itemId, meta)

To clear item's categories, call UpdateItem with an empty list:

// create EWS client instance, connect, log in
// ...

// prepare metadata to unset all categories from an item
var meta = new EwsItemMetadata();

// set empty collection to unset all categories
meta.Categories = new EwsCategoryCollection();

// update item metadata
ews.UpdateItem(itemId, meta);
' create EWS client instance, connect, log in
' ...

' prepare metadata to unset all categories from an item
Dim meta = New EwsItemMetadata()

' set empty collection to unset all categories
meta.Categories = New EwsCategoryCollection()

' update item metadata
ews.UpdateItem(itemId, meta)

Once assigned, the categories can be searched:

// search all messages Joe is working on
// (Joe AND NOT Completed)
var working = ews.SearchItems(folderId,
    EwsPageView.CreateIndexed(0, 1),
        EwsSearchParameter.Category("Joe"),
        EwsSearchParameter.Not(
            EwsSearchParameter.HasFlag(EwsFlagStatus.Completed)));

// search all messages Joe completed already
// (Joe AND Completed)
var solved = ews.SearchItems(folderId,
    EwsPageView.CreateIndexed(0, 1),
        EwsSearchParameter.Category("Joe"),
        EwsSearchParameter.HasFlag(EwsFlagStatus.Completed));

// write info
Console.WriteLine("Joe is working on {0} item(s)", working.PageResult.ItemsTotal);
Console.WriteLine("Joe completed {0} item(s)", solved.PageResult.ItemsTotal);
' search all messages Joe is working on
' (Joe AND NOT Completed)
Dim working = ews.SearchItems(folderId,
    EwsPageView.CreateIndexed(0, 1),
        EwsSearchParameter.Category("Joe"),
        EwsSearchParameter.Not(
            EwsSearchParameter.HasFlag(EwsFlagStatus.Completed)))

' search all messages Joe completed already
' (Joe AND Completed)
Dim solved = ews.SearchItems(folderId,
    EwsPageView.CreateIndexed(0, 1),
        EwsSearchParameter.Category("Joe"),
        EwsSearchParameter.HasFlag(EwsFlagStatus.Completed))

' write info
Console.WriteLine("Joe is working on {0} item(s)", working.PageResult.ItemsTotal)
Console.WriteLine("Joe completed {0} item(s)", solved.PageResult.ItemsTotal)

Attachments - adding, getting, deleting 

Exchange attachments are distinct objects identified by attachment IDs represented by EwsAttachmentId object.

To add an attachment to a message or an item, use AddAttachment method:

// create EWS client instance, connect, log in
// ...

// add a file as an attachment to an item
ews.AddAttachment(itemId, @"C:\data\file.txt");

// add a mail message as an attachment to an item
MailMessage message = new MailMessage();
message.Subject = "Empty mail";
ews.AddAttachment(itemId, message);
' create EWS client instance, connect, log in
' ...

' add a file as an attachment to an item
ews.AddAttachment(itemId, "C:\data\file.txt")

' add a mail message as an attachment to an item
Dim message As New MailMessage()
message.Subject = "Empty mail"
ews.AddAttachment(itemId, message)

Tip: AddAttachment method returns the ID of the new attachment.

To remove an attachment (both from its message/item and Exchange server), use DeleteAttachment method:

// delete an attachment from an item
ews.DeleteAttachment(attachmentId);
' delete an attachment from an item
ews.DeleteAttachment(attachmentId)

To retrieve a list of item's or message's attachments, use GetItemInfo or GetMessageInfo methods. To retrieve the attachment including its content, use GetAttachment method:

// get info about all attachments of the item
EwsItemInfo item = ews.GetItemInfo(itemId, EwsItemFields.AttachmentInfo);

// print info about attachments
Console.WriteLine("Item has {0} attachment(s)", item.Attachments.Count);
foreach (EwsAttachmentInfo att in item.Attachments)
{
    Console.WriteLine(" {0} <{1}> ~{2}B", att.Name, att.ContentType, att.Size);
}

// get ID of first attachment
EwsAttachmentId attachmentId = item.Attachments[0].Id;

// get fully featured attachment object
Attachment attachment = ews.GetAttachment(attachmentId);

// save the attachment
attachment.Save(Path.Combine(@"C:\data", attachment.FileName));
' get info about all attachments of the item
Dim item As EwsItemInfo = ews.GetItemInfo(itemId, EwsItemFields.AttachmentInfo)

' print info about attachments
Console.WriteLine("Item has {0} attachment(s)", item.Attachments.Count)
For Each att As EwsAttachmentInfo In item.Attachments
    Console.WriteLine(" {0} <{1}> ~{2}B", att.Name, att.ContentType, att.Size)
Next

' get ID of first attachment
Dim attachmentId As EwsAttachmentId = item.Attachments(0).Id

' get fully featured attachment object
Dim attachment As Attachment = ews.GetAttachment(attachmentId)

' save the attachment
attachment.Save(Path.Combine("C:\data", attachment.FileName))

Searching for messages 

Use Search method to search for messages matching the specified criteria. Check out Searching section for more information.

Exchange IDs (Item, Folder and Attachment IDs) 

Exchange server distinguishes three basic types of items. In Rebex Secure Mail, these three types are represented by different classes:

  • Folder - EwsFolderId - mailbox folders and subfolders (such as 'Inbox', 'Sent Items' or 'Drafts').
  • Item - EwsItemId - messages and other items (such as contacts, appointments or tasks).
  • Attachment - EwsAttachmentId - attachments of other items or mail messages.

Every ID consists of two parts:

  • Id - a unique identifier of a folder, item or attachment.
  • ChangeKey - identifies a specific version of the folder, item or attachment. This part is optional and most methods ignore it. However, it's required for SendMessage and UpdateItem methods and must be set to the current value.

These IDs are available as Id property of EwsFolderInfo, EwsAttachmentInfo, EwsItemInfo and EwsMessageInfo classes. There are also several pre-defined folder IDs that can be used to access well-known folders.

// create EWS client instance, connect, log in
var ews = new Rebex.Net.Ews();
ews.Connect(hostname);
ews.Login(username, password);

// get a list of messages
EwsMessageCollection messages = ews.GetMessageList(EwsFolderId.Inbox);

// get information about the first one
EwsMessageInfo message = messages[0];

// print information about its ID
EwsItemId messageId = message.Id;
Console.WriteLine("ID: {0}", messageId.Value);
Console.WriteLine("Change Key: {0}", messageId.ChangeKey);
Console.WriteLine("Native Exchange ID: {0}", messageId.GetNativeValue());
Console.WriteLine("Native Exchange Change Key: {0}", messageId.GetNativeChangeKey());
' create EWS client instance, connect, log in
Dim ews = New Rebex.Net.Ews()
ews.Connect(hostname)
ews.Login(username, password)

' get a list of messages
Dim messages As EwsMessageCollection = ews.GetMessageList(EwsFolderId.Inbox)

' get information about the first one
Dim message As EwsMessageInfo = messages(0)

' print information about its ID
Dim messageId As EwsItemId = message.Id
Console.WriteLine("ID: {0}", messageId.Value)
Console.WriteLine("Change Key: {0}", messageId.ChangeKey)
Console.WriteLine("Native Exchange ID: {0}", messageId.GetNativeValue())
Console.WriteLine("Native Exchange Change Key: {0}", messageId.GetNativeChangeKey())

Note: In Rebex Secure Mail, IDs and change keys are represented as filename-friendly and case-insensitive strings. To retrieve IDs and change keys in Exchange Base64-encoded format, use GetNativeValue and GetNativeChangeKey methods.

Note: EwsMessageInfo and MailMessage classes feature MessageId property. This represents MIME Message-Id that is not related to Exchange item or message IDs.

Message fields 

Many Ews methods make it possible to specify which information to retrieve about an item or a message. These methods include GetMessageInfo, GetItemInfo, GetMessageList, GetItemList or Search. It's a good idea to only request the information you need - it can save lot of time, bandwidth and processing power. Use the EwsItemFields argument to specify which information to retrieve:

Parameter value Description
EwsItemFields.Default Default set of fields defined by Exchange server. This is the default for methods with optional fields argument.
EwsItemFields.Id Only retrieve item ID.
EwsItemFields.Fast Retrieve item ID, size and receive date.
EwsItemFields.All All fields relevant for the operation.
EwsItemFields.Envelope Same as Fast, but retrieves message envelope info as well. This includes the most important header fields such as Date, From, To, Subject or Message-ID.
This parameter is only valid for GetItemInfo and GetMessageInfo methods.
EwsItemFields.AttachmentInfo Retrieves information about attachments.
This parameter is only valid for GetItemInfo and GetMessageInfo methods.
EwsItemFields.Body Retrieves message body (HTML if available, plain text otherwise).
This parameter is only valid for GetItemInfo and GetMessageInfo methods.
EwsItemFields.TextBody Retrieves message body in plain text format.
This parameter is only valid for GetItemInfo and GetMessageInfo methods.

Note: These fields are bit flags, which means that combinations such as Envelope | Body are possible - use bitwise OR operator for this (| in C#, Or in VB.NET).

The following code shows how to combine multiple EwsItemFields to get desired results:

// create EWS client instance, connect, log in
// ...

// get Envelope and Attachment info
EwsMessageInfo message = ews.GetMessageInfo(
    messageId, EwsItemFields.Envelope | EwsItemFields.AttachmentInfo);

// print some info about the message
Console.WriteLine("From: {0}", message.From);
Console.WriteLine("To: {0}", message.To);
Console.WriteLine("Subject: {0}", message.Subject);
Console.WriteLine("Size: {0}kB", message.Size / 1024);
if (message.HasAttachments)
{
    Console.WriteLine("Attachments:");
    foreach (EwsAttachmentInfo item in message.Attachments)
    {
        Console.WriteLine(" {0} <{1}>", item.Name, item.ContentType);
    }
}
' create EWS client instance, connect, log in
' ...

' get Envelope and Attachment info
Dim message As EwsMessageInfo = ews.GetMessageInfo(
    itemId, EwsItemFields.Envelope Or EwsItemFields.AttachmentInfo)

' print some info about the message
Console.WriteLine("From: {0}", message.From)
Console.WriteLine("To: {0}", message.[To])
Console.WriteLine("Subject: {0}", message.Subject)
Console.WriteLine("Size: {0}kB", message.Size / 1024)
If message.HasAttachments Then
    Console.WriteLine("Attachments:")
    For Each item As EwsAttachmentInfo In message.Attachments
        Console.WriteLine(" {0} <{1}>", item.Name, item.ContentType)
    Next
End If

Back to feature list...