Working with Exchange Mailbox and Messages

Getting Mailbox Information Using EWS

You can get mailbox information from an Exchange Server by calling the GetMailboxInfo method of the IEWSClient class. It returns an instance of type ExchangeMailboxInfo. Get mailbox information from properties such as MailboxUri, InboxUri, and DraftsUri. This article shows how to access mailbox information using Exchange Web Services.

To connect to the Exchange Server using Exchange Web Services (EWS), use the IEWSClient class. This class uses EWS to connect to and manage items on an Exchange Server. The following code snippet shows you how to get mailbox information using the exchange web services.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of EWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Get mailbox size, exchange mailbox info, Mailbox and Inbox folder URI
System::Console::WriteLine(System::String(u"Mailbox size: ") + client->GetMailboxSize() + u" bytes");
System::SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
System::Console::WriteLine(System::String(u"Mailbox URI: ") + mailboxInfo->get_MailboxUri());
System::Console::WriteLine(System::String(u"Inbox folder URI: ") + mailboxInfo->get_InboxUri());
System::Console::WriteLine(System::String(u"Sent Items URI: ") + mailboxInfo->get_SentItemsUri());
System::Console::WriteLine(System::String(u"Drafts folder URI: ") + mailboxInfo->get_DraftsUri());

Sending Email Messages

You can send email messages using an Exchange Server with the IEWSClient->Send() method accepts a MailMessage instance as a parameter and sends the email. This article explains how to send email messages using Exchange Web Services.

The following code snippet shows you how to sends email messages using IEWSClient.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of IEWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Create instance of type MailMessage
System::SharedPtr<MailMessage> msg = System::MakeObject<MailMessage>();
msg->set_From(MailAddress::to_MailAddress(u"sender@domain.com"));
msg->set_To(MailAddressCollection::to_MailAddressCollection(u"recipient@ domain.com "));
msg->set_Subject(u"Sending message from exchange server");
msg->set_HtmlBody(u"<h3>sending message from exchange server</h3>");
// Send the message
client->Send(msg);

Reading Emails from other User’s Mailbox

Some accounts on Exchange Servers have the right to access multiple mailboxes, and some users have multiple email accounts on the same Exchange Server. In both cases, users can access other user’s mailboxes using Aspose.Email. This API provides a mechanism for accessing folders and emails from other mailboxes using the IEWSClient class. This functionality can be achieved using the overloaded GetMailboxInfo() method and providing the user email address as a parameter.

The following code snippet shows you how to read emails using the IEWSClient class.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of EWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Get Exchange mailbox info of other email account
System::SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo(u"otherUser@domain.com");

Listing Messages

A list of the email messages in an Exchange mailbox can be fetched by calling the ListMessages method. Get the basic information about messages, such as subject, from, to and message ID, using the ListMessages method.

Simple Messages Listing

To list the messages in an Exchange mailbox:

  1. Create an instance of the IEWSClient class.
  2. Call the ListMessages method to get the message collection.
  3. Loop through the collection and display message information.

The following code snippet shows you how to connect to an exchange server using EWS and lists messages from the inbox folder.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of ExchangeWebServiceClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
// Loop through the collection to display the basic information
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::Console::WriteLine(System::String(u"Subject: ") + msgInfo->get_Subject());
if (msgInfo->get_From() != nullptr)
System::Console::WriteLine(System::String(u"From: ") + msgInfo->get_From()->ToString());
System::Console::WriteLine(System::String(u"To: ") + msgInfo->get_To()->ToString());
System::Console::WriteLine(System::String(u"Message ID: ") + msgInfo->get_MessageId());
System::Console::WriteLine(System::String(u"Unique URI: ") + msgInfo->get_UniqueUri());
}

Listing Messages From Different Folders

The above code snippet list all the messages in the Inbox folder. It is possible to get the list of messages from other folders as well. The ListMessages method accepts a folder URI as a parameter. As long as the folder URI is valid, you can get the list of messages from that folder. Use the IEWSClient->get_MailboxInfo->xxxFolderUri property to get the URI of different folders. The rest of the code is the same as for getting a list of messages. The following code snippet shows you how to list messages from different folders using EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of EWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Get folder URI
System::String strFolderURI = System::String::Empty;
strFolderURI = client->get_MailboxInfo()->get_InboxUri();
strFolderURI = client->get_MailboxInfo()->get_DeletedItemsUri();
strFolderURI = client->get_MailboxInfo()->get_DraftsUri();
strFolderURI = client->get_MailboxInfo()->get_SentItemsUri();
// Get list of messages from the specified folder
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(strFolderURI);

Listing Messages with Paging Support

The following code snippet shows you how to get a list of messages with paging support.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Create some test messages to be added to server for retrieval later
int32_t messagesNum = 12;
int32_t itemsPerPage = 5;
System::SharedPtr<MailMessage> message;
for (int32_t i = 0; i < messagesNum; i++)
{
message = System::MakeObject<MailMessage>(u"from@domain.com", u"to@domain.com", System::String(u"EMAILNET-35157_1 - ") + System::ObjectExt::ToString(System::Guid::NewGuid()), u"EMAILNET-35157 Move paging parameters to separate class");
client->AppendMessage(client->get_MailboxInfo()->get_InboxUri(), message);
}
// Verfiy that the messages have been added to the server
System::SharedPtr<ExchangeMessageInfoCollection> totalMessageInfoCol = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
System::Console::WriteLine(totalMessageInfoCol->get_Count());
/// /////////////// RETREIVING THE MESSAGES USING PAGING SUPPORT ////////////////////////////////////
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<ExchangeMessagePageInfo>>> pages = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<ExchangeMessagePageInfo>>>();
System::SharedPtr<ExchangeMessagePageInfo> pageInfo = client->ListMessagesByPage(client->get_MailboxInfo()->get_InboxUri(), itemsPerPage);
// Total Pages Count
System::Console::WriteLine(pageInfo->get_TotalCount());
pages->Add(pageInfo);
while (!pageInfo->get_LastPage())
{
pageInfo = client->ListMessagesByPage(client->get_MailboxInfo()->get_InboxUri(), itemsPerPage, pageInfo->get_PageOffset() + 1);
pages->Add(pageInfo);
}
int32_t retrievedItems = 0;
for (auto pageCol : System::IterateOver(pages))
{
retrievedItems += pageCol->get_Items()->get_Count();
}
// Verify total message count using paging
System::Console::WriteLine(retrievedItems);

Getting Message Type Information from ExchangeMessageInfo

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
const System::String mailboxUri = u"https://exchange/ews/exchange.asmx";
const System::String domain = u"";
const System::String username = u"username@ASE305.onmicrosoft.com";
const System::String password = u"password";
System::SharedPtr<System::Net::NetworkCredential> credentials = System::MakeObject<System::Net::NetworkCredential>(username, password, domain);
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<ExchangeMessageInfoCollection> list = client->ListMessages(client->get_MailboxInfo()->get_DeletedItemsUri());
System::Console::WriteLine(System::ObjectExt::ToString(list->idx_get(0)->get_MessageInfoType()));

Saving Messages

This article shows how to get messages from an Exchange Server mailbox and save them to disk in EML and MSG formats:

  • Save as EML on disk.
  • Save to memory stream.
  • Save as MSG.

Saving Messages to EML

To get messages and save in EML format:

  1. Create an instance of the IEWSClient class.
  2. Provide the mailboxUri, username, password and domain.
  3. Call the IEWSClient->ListMessages() method to get an instance of the ExchangeMessagesInfoCollection collection.
  4. Loop through the ExchangeMessagesInfoCollection collection to get the unique URI for each message.
  5. Call the IEWSClient->SaveMessage() method and pass the unique URI and save location as parameters.

The following code snippet shows you how to use EWS to connect to the Exchange Server and save messages as EML files.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
System::String dataDir = GetDataDir_Exchange();
// Create instance of IEWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
// Loop through the collection to get Message URI
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::String strMessageURI = msgInfo->get_UniqueUri();
// Now save the message in disk
client->SaveMessage(strMessageURI, dataDir + msgInfo->get_MessageId() + u"out.eml");
}

Saving Messages to a Memory Stream

Instead of saving EML files to disk, it is possible to save it to a memory stream. This is useful when you want to save the stream to some storage location like a database. Once the stream has been saved to a database, you can reload the EML file into the MailMessage class. The following code snippet shows you how to save messages from an Exchange Server mailbox to a memory stream using EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
// Loop through the collection to get Message URI
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::String strMessageURI = msgInfo->get_UniqueUri();
// Now save the message in memory stream
System::SharedPtr<System::IO::MemoryStream> stream = System::MakeObject<System::IO::MemoryStream>();
client->SaveMessage(strMessageURI, datadir + stream);
}

Saving Messages in MSG Format

The IEWSClient->SaveMessage() method can directly save the message to EML format. To save the messages to MSG format, first, call the IEWSClient->FetchMessage() method which returns an instance of the MailMessage class. Then call the MailMessage->Save() method to save the message to MSG. The following code snippet shows you how to get messages from an Exchange Server mailbox and saves them to MSG format using EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of EWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
int32_t count = 0;
// Loop through the collection to get Message URI
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::String strMessageURI = msgInfo->get_UniqueUri();
// Now get the message details using FetchMessage() and Save message as Msg
System::SharedPtr<MailMessage> message = client->FetchMessage(strMessageURI);
message->Save(dataDir + (count++) + u"_out.msg", SaveOptions::get_DefaultMsgUnicode());
}

Getting ExchangeMessageInfo from Message URI

An email message is represented by its unique identifier, URI, and is an integral part of the ExchangeMessageInfo object. In case, only message URI is available, then ExchangeMessageInfo object can also be retrieved using this available information. The overload version of ListMessages takes a list of Ids and returns an ExchangeMessageInfoCollection collection. The following code snippet shows you how to get ExchangeMessageInfo from message URI.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<System::Collections::Generic::List<System::String>> ids = System::MakeObject<System::Collections::Generic::List<System::String>>();
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<MailMessage>>> messages = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<MailMessage>>>();
for (int32_t i = 0; i < 5; i++)
{
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>(u"user@domain.com", u"receiver@domain.com", System::String(u"EMAILNET-35033 - ") + System::ObjectExt::ToString(System::Guid::NewGuid()), u"EMAILNET-35033 Messages saved from Sent Items folder doesn't contain 'To' field");
messages->Add(message);
System::String uri = client->AppendMessage(message);
ids->Add(uri);
}
System::SharedPtr<ExchangeMessageInfoCollection> messageInfoCol = client->ListMessages(ids);
for (auto messageInfo : System::IterateOver(messageInfoCol))
{
// Do something ...
System::Console::WriteLine(messageInfo->get_UniqueUri());
}

Fetch Messages from an Exchange Server Mailbox

The ListMessages() method is used to get a list of messages from an Exchange Server mailbox. The ListMessages() method gets basic information about messages, for example, the subject, the message ID, from, and to. To get the complete message details, Aspose.Email provides the IEWSClient->FetchMessage() method. This method accepts the message URI as a parameter and returns an instance of the MailMessage class. The MailMessage class then provides message details like the body, headers, and attachments. To fetch messages from Exchange Server Mailbox:

  1. Create an instance of type IEWSClient.
  2. Specify the server name, user name, password, and domain.
  3. Call IEWSClient->ListMessages() method to get the ExchangeMessagesInfoCollection.
  4. Loop through the ExchangeMessagesInfoCollection collection to get ExchangeMessageInfo->get_UniqueUri() values.
  5. Call IEWSClient->FetchMessage() and pass ExchangeMessageInfo->get_UniqueUri() as parameter.

The following code snippet demonstrates fetching all the messages using EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of ExchangeWebServiceClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
// Loop through the collection to get Message URI
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::String strMessageURI = msgInfo->get_UniqueUri();
// Now get the message details using FetchMessage()
System::SharedPtr<MailMessage> msg = client->FetchMessage(strMessageURI);
for (auto att : System::IterateOver(msg->get_Attachments()))
{
System::Console::WriteLine(System::String(u"Attachment Name: ") + att->get_Name());
}
}

Pre-Fetch Message Size

Microsoft Outlook InterOp provides the feature of retrieving message size before actually fetching the complete message from the server. In case of Aspose.Email API, the summary information retrieved from the Exchange server is represented by the ExchangeMessageInfo class. It provides the feature of retrieving message size by using the Size property. In order to retrieve the message size, the standard call to IEWSClient->ListMessages() is used to retrieve the ExchangeMessagesInfoCollection. The following code snippet shows you how to display message size using the ExchangeMessageInfo class.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of ExchangeWebServiceClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
// Call ListMessages method to list messages info from Inbox
System::SharedPtr<ExchangeMessageInfoCollection> msgCollection = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
// Loop through the collection to display the basic information
for (auto msgInfo : System::IterateOver(msgCollection))
{
System::Console::WriteLine(System::String(u"Subject: ") + msgInfo->get_Subject());
if (msgInfo->get_From() != nullptr)
System::Console::WriteLine(System::String(u"From: ") + msgInfo->get_From()->ToString());
if (msgInfo->get_To() != nullptr)
System::Console::WriteLine(System::String(u"To: ") + msgInfo->get_To()->ToString());
System::Console::WriteLine(System::String(u"Message Size: ") + msgInfo->get_Size());
System::Console::WriteLine(u"==================================");
}

Download Messages from Public Folders

Microsoft Exchange Server lets users create public folders and post messages in them. To do this through your application, use Aspose.Email’s 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 reads 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-C
static String dataDir = GetDataDir_Exchange();
String username;
String password;
String domain;
String mailboxUri;
void ListMessagesFromSubFolder(System::SharedPtr<Aspose::Email::Clients::Exchange::ExchangeFolderInfo> publicFolder, System::SharedPtr<Aspose::Email::Clients::Exchange::WebService::IEWSClient> client)
{
System::Console::WriteLine(System::String(u"Folder Name: ") + publicFolder->get_DisplayName());
System::SharedPtr<ExchangeMessageInfoCollection> msgInfoCollection = client->ListMessagesFromPublicFolder(publicFolder);
for (auto messageInfo : System::IterateOver(msgInfoCollection))
{
System::SharedPtr<MailMessage> msg = client->FetchMessage(messageInfo->get_UniqueUri());
System::Console::WriteLine(msg->get_Subject());
msg->Save(dataDir + msg->get_Subject() + u".msg", SaveOptions::get_DefaultMsgUnicode());
}
// Call this method recursively for any subfolders
if (publicFolder->get_ChildFolderCount() > 0)
{
System::SharedPtr<ExchangeFolderInfoCollection> subfolders = client->ListSubFolders(publicFolder);
for (System::SharedPtr<Aspose::Email::Clients::Exchange::ExchangeFolderInfo> subfolder : System::IterateOver(subfolders))
{
ListMessagesFromSubFolder(subfolder, client);
}
}
}
void ReadPublicFolders()
{
System::SharedPtr<System::Net::NetworkCredential> credential = System::MakeObject<System::Net::NetworkCredential>(username, password, domain);
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<ExchangeFolderInfoCollection> folders = client->ListPublicFolders();
for (auto publicFolder : System::IterateOver(folders))
{
System::Console::WriteLine(System::String(u"Name: ") + publicFolder->get_DisplayName());
System::Console::WriteLine(System::String(u"Subfolders count: ") + publicFolder->get_ChildFolderCount());
ListMessagesFromSubFolder(publicFolder, client);
}
}
void DownloadMessagesFromPublicFolders()
{
try
{
ReadPublicFolders();
}
catch (System::Exception& ex)
{
System::Console::WriteLine(ex.get_Message());
}
}

Moving Messages

You can move email messages from one folder to another with the help of the IEWSClient class Move method. It takes the following parameters:

  • The unique URI of the message which is to be moved.
  • The unique URI of the destination folder.

Moving Messages between Folders

The following code snippet shows you how to move a message in a mailbox from the Inbox folder to a folder called Processed. In this example, the application:

  1. Reads messages from the Inbox folder.
  2. Processes some of the messages based on some criteria (in this example, we find a keyword in the message subject).
  3. Moves messages which fulfill the given condition to the processed folder.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of IEWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
// List all messages from Inbox folder
System::Console::WriteLine(u"Listing all messages from Inbox....");
System::SharedPtr<ExchangeMessageInfoCollection> msgInfoColl = client->ListMessages(mailboxInfo->get_InboxUri());
for (auto msgInfo : System::IterateOver(msgInfoColl))
{
// Move message to "Processed" folder, after processing certain messages based on some criteria
if (msgInfo->get_Subject() != nullptr && msgInfo->get_Subject().ToLower().Contains(u"process this message") == true)
{
client->MoveItem(mailboxInfo->get_DeletedItemsUri(), msgInfo->get_UniqueUri());
// EWS
System::Console::WriteLine(System::String(u"Message moved....") + msgInfo->get_Subject());
}
else { }
}

Deleting Messages

You can delete email messages from a folder with the help of the IEWSClient->DeleteMessage method. It takes the message’s unique URI as a parameter.

The following code snippet shows you how to delete a message from the Inbox folder. For the purpose of this example, the code:

  1. Reads messages from the Inbox folder.
  2. Process messages based on some criteria (in this example, we find a keyword in the message subject).
  3. Deletes the message.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
// Create instance of IEWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
// List all messages from Inbox folder
System::Console::WriteLine(u"Listing all messages from Inbox....");
System::SharedPtr<ExchangeMessageInfoCollection> msgInfoColl = client->ListMessages(mailboxInfo->get_InboxUri());
for (auto msgInfo : System::IterateOver(msgInfoColl))
{
// Delete message based on some criteria
if (msgInfo->get_Subject() != nullptr && msgInfo->get_Subject().ToLower().Contains(u"delete") == true)
{
client->DeleteMessage(msgInfo->get_UniqueUri());
// EWS
System::Console::WriteLine(System::String(u"Message deleted....") + msgInfo->get_Subject());
}
else { }
}

Copying Messages

Aspose.Email API allows copying a message from one folder to another folder using the IEWSClient->CopyItem method. The overloaded version of this method returns the Unique URI of the copied message as shown in this article.

Copying a Message to Another Folder

The following code snippet shows you how to copy a message to another folder.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C
try
{
// Create instance of EWSClient class by giving credentials
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser());
System::SharedPtr<MailMessage> message = System::MakeObject<MailMessage>(u"from@domain.com", u"to@domain.com", System::String(u"EMAILNET-34997 - ") + System::ObjectExt::ToString(System::Guid::NewGuid()), u"EMAILNET-34997 Exchange: Copy a message and get reference to the new Copy item");
System::String messageUri = client->AppendMessage(message);
System::String newMessageUri = client->CopyItem(messageUri, client->get_MailboxInfo()->get_DeletedItemsUri());
}
catch (System::Exception& ex)
{
System::Console::WriteLine(ex.get_Message());
}