Send, Read, and Organize Messages on Exchange Server
The IEWSClient class connects to Microsoft Exchange Server through Exchange Web Services (EWS) and works with the messages of a mailbox: it lists, reads, saves, sends, moves, copies and deletes them. Messages on the server are identified by their unique URI, which the listing methods return in ExchangeMessageInfo objects.
The samples in this article use these headers and namespaces:
#include <MailMessage.h>
#include <MailAddress.h>
#include <MailAddressCollection.h>
#include <Attachment.h>
#include <AttachmentCollection.h>
#include <SaveOptions.h>
#include <MsgSaveOptions.h>
#include <Clients/Exchange/WebService/EWSClient/EWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/IEWSClient.h>
#include <Clients/Exchange/WebService/EWSClient/DeletionOptions.h>
#include <Clients/Exchange/ExchangeMailboxInfo.h>
#include <Clients/Exchange/ExchangeMessageInfo.h>
#include <Clients/Exchange/ExchangeMessageInfoCollection.h>
#include <Clients/Exchange/ExchangeMessagePageInfo.h>
#include <Clients/Exchange/ExchangeFolderInfo.h>
#include <Clients/Exchange/ExchangeFolderInfoCollection.h>
#include <Clients/Exchange/MessageInfoType.h>
#include <system/io/memory_stream.h>
#include <system/collections/list.h>
#include <system/convert.h>
#include <system/object_ext.h>
using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Clients::Exchange;
using namespace Aspose::Email::Clients::Exchange::WebService;
Retrieve Exchange Mailbox Information with EWS
GetMailboxInfo() returns an ExchangeMailboxInfo object with the URIs of the mailbox and of its standard folders - Inbox, Sent Items, Drafts and others. These URIs are the folder arguments of the other methods of the client. GetMailboxSize() returns the size of the mailbox in bytes.
The following code snippet demonstrates how to get mailbox information using Exchange Web Services.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
Console::WriteLine(u"Mailbox size: " + Convert::ToString(client->GetMailboxSize()) + u" bytes");
SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
Console::WriteLine(u"Mailbox URI: " + mailboxInfo->get_MailboxUri());
Console::WriteLine(u"Inbox folder URI: " + mailboxInfo->get_InboxUri());
Console::WriteLine(u"Sent Items URI: " + mailboxInfo->get_SentItemsUri());
Console::WriteLine(u"Drafts folder URI: " + mailboxInfo->get_DraftsUri());
client->Dispose();
Send Email Messages via EWS
You can send emails through Exchange by calling the IEWSClient->Send() method. It takes a MailMessage object and submits it directly through the server using EWS.
The following code sample creates an HTML message with a sender, a recipient and a subject, and sends it through Exchange.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
SharedPtr<MailMessage> message = MakeObject<MailMessage>();
message->set_From(MakeObject<MailAddress>(u"sender@domain.com"));
message->get_To()->Add(u"recipient@domain.com");
message->set_Subject(u"Sending message from exchange server");
message->set_HtmlBody(u"<h3>sending message from exchange server</h3>");
client->Send(message);
client->Dispose();
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 users’ mailboxes with Aspose.Email. The overload of GetMailboxInfo() that takes an e-mail address returns the folder URIs of that mailbox; the client then works with its folders like with its own.
The following code snippet lists the Inbox of another mailbox.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo(u"otherUser@domain.com");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(mailboxInfo->get_InboxUri()))
{
Console::WriteLine(messageInfo->get_Subject());
}
client->Dispose();
List Messages Using EWS
Aspose.Email for C++ allows you to retrieve message metadata from Exchange Server mailboxes through the IEWSClient. Using the EWS-based ListMessages API, you can list messages from any folder, browse message metadata, and implement paging for large mailboxes.
List Messages from the Inbox
Use ListMessages to retrieve basic message information such as subject, sender, recipients, and message ID from the Inbox or any folder.
- Create an instance of IEWSClient.
- Call ListMessages with the target folder URI.
- Iterate through ExchangeMessageInfoCollection.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
SharedPtr<ExchangeMessageInfoCollection> messages = client->ListMessages(client->get_MailboxInfo()->get_InboxUri());
for (SharedPtr<ExchangeMessageInfo> messageInfo : messages)
{
Console::WriteLine(u"Subject: " + messageInfo->get_Subject());
if (messageInfo->get_From() != nullptr)
{
Console::WriteLine(u"From: " + messageInfo->get_From()->ToString());
}
if (messageInfo->get_To() != nullptr)
{
Console::WriteLine(u"To: " + messageInfo->get_To()->ToString());
}
Console::WriteLine(u"Message ID: " + messageInfo->get_MessageId());
Console::WriteLine(u"Unique URI: " + messageInfo->get_UniqueUri());
}
client->Dispose();
List Messages from Any Folder
ListMessages accepts any valid folder URI, allowing you to list items from Deleted Items, Drafts, Sent Items, or custom folders. The URIs of the standard folders come from client->get_MailboxInfo(): get_InboxUri(), get_DeletedItemsUri(), get_DraftsUri(), get_SentItemsUri() and so on.
The following code sample lists the messages of the Sent Items folder.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
String folderUri = client->get_MailboxInfo()->get_SentItemsUri();
SharedPtr<ExchangeMessageInfoCollection> messages = client->ListMessages(folderUri);
Console::WriteLine(u"Messages in Sent Items: " + Convert::ToString(messages->get_Count()));
client->Dispose();
Pagination in Message Listing
For large mailboxes, use ListMessagesByPage to load messages in smaller blocks.
- The first call takes the folder URI and the number of items per page and returns the first page as an ExchangeMessagePageInfo.
- Each next call also takes the offset of the page to read: the offset of the previous page plus one.
- The listing stops at the page whose
get_LastPage()returnstrue.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
const int32_t itemsPerPage = 5;
String inboxUri = client->get_MailboxInfo()->get_InboxUri();
SharedPtr<ExchangeMessagePageInfo> pageInfo = client->ListMessagesByPage(inboxUri, itemsPerPage);
Console::WriteLine(u"Total messages: " + Convert::ToString(pageInfo->get_TotalCount()));
int32_t retrievedItems = pageInfo->get_Items()->get_Count();
while (!pageInfo->get_LastPage())
{
pageInfo = client->ListMessagesByPage(inboxUri, itemsPerPage, pageInfo->get_PageOffset() + 1);
retrievedItems += pageInfo->get_Items()->get_Count();
}
Console::WriteLine(u"Retrieved: " + Convert::ToString(retrievedItems));
client->Dispose();
Get Message Type Information
ExchangeMessageInfo::get_MessageInfoType() returns the type of the item on the server as a MessageInfoType value - an e-mail message, a meeting request and so on.
The following code sample shows the type of each item in the Deleted Items folder.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_DeletedItemsUri()))
{
Console::WriteLine(messageInfo->get_Subject() + u": " + ObjectExt::ToString(messageInfo->get_MessageInfoType()));
}
client->Dispose();
Save Messages Using Exchange Web Services (EWS)
Aspose.Email enables you to retrieve messages from an Exchange Server mailbox and save them in multiple formats, such as EML, memory streams, and MSG. The examples below demonstrate how to fetch message information and store messages using the IEWSClient API.
Save Messages as EML Files
To save mailbox messages as EML files:
- Create an IEWSClient instance using valid credentials.
- Call ListMessages() to retrieve an ExchangeMessageInfoCollection.
- Loop through the collection to access each message unique URI.
- Call SaveMessage() to store each message on disk in EML format.
The file names below are numbered, because message IDs and subjects can contain characters that are not allowed in file names.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
int32_t count = 0;
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
client->SaveMessage(messageInfo->get_UniqueUri(), Convert::ToString(count++) + u"_out.eml");
}
client->Dispose();
Save Messages to a Memory Stream
Instead of writing to disk, you can save messages to a memory stream - useful for storing emails in a database or processing them in memory. The overload of SaveMessage() that takes a stream writes the message to it in EML format.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
SharedPtr<IO::MemoryStream> stream = MakeObject<IO::MemoryStream>();
client->SaveMessage(messageInfo->get_UniqueUri(), stream);
Console::WriteLine(messageInfo->get_Subject() + u": " + Convert::ToString(stream->get_Length()) + u" bytes");
}
client->Dispose();
Save Messages in MSG Format
To save messages as MSG:
- Retrieve the message using FetchMessage(), which returns a MailMessage.
- Call MailMessage::Save() with MSG save options, such as SaveOptions::get_DefaultMsgUnicode().
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
int32_t count = 0;
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
SharedPtr<MailMessage> message = client->FetchMessage(messageInfo->get_UniqueUri());
message->Save(Convert::ToString(count++) + u"_out.msg", SaveOptions::get_DefaultMsgUnicode());
}
client->Dispose();
Retrieve Message Details by Message URI
When only a message unique URI is available, you can still retrieve full ExchangeMessageInfo objects. The IEWSClient::ListMessages() overload accepts a list of message IDs (URIs) and returns an ExchangeMessageInfoCollection. Use this feature when you store or receive message URIs externally and need to load metadata (subject, sender, size, etc.) without fetching full messages.
The following code sample appends several messages to the Inbox with AppendMessage(), keeps the URIs it returns and then reads the information about these messages.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
SharedPtr<Collections::Generic::List<String>> ids = MakeObject<Collections::Generic::List<String>>();
for (int32_t i = 0; i < 5; i++)
{
SharedPtr<MailMessage> message = MakeObject<MailMessage>(u"user@domain.com", u"receiver@domain.com",
u"Message " + Convert::ToString(i), u"Message body");
ids->Add(client->AppendMessage(message));
}
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(ids))
{
Console::WriteLine(messageInfo->get_Subject() + u": " + messageInfo->get_UniqueUri());
}
client->Dispose();
Fetch Full Message Content
ListMessages() returns summary information (subject, sender, IDs). To load full message content - body, headers, attachments - use FetchMessage().
The following code sample fetches the messages of the Inbox and shows the names of their attachments:
- Create an IEWSClient instance.
- Call ListMessages() to get basic message metadata.
- Take the unique URI of each message.
- Call FetchMessage() to retrieve full message details.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
SharedPtr<MailMessage> message = client->FetchMessage(messageInfo->get_UniqueUri());
for (SharedPtr<Attachment> attachment : message->get_Attachments())
{
Console::WriteLine(u"Attachment Name: " + attachment->get_Name());
}
}
client->Dispose();
Fetch Message Size (Without Downloading Full Message)
Aspose.Email provides message size information without fetching the entire email, through the ExchangeMessageInfo::get_Size() property.
This is useful for:
- mailbox statistics
- quota calculations
- filtering large messages before downloading
The following code sample lists the messages of the Inbox together with their sizes.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
Console::WriteLine(u"Subject: " + messageInfo->get_Subject());
if (messageInfo->get_From() != nullptr)
{
Console::WriteLine(u"From: " + messageInfo->get_From()->ToString());
}
Console::WriteLine(u"Message Size: " + Convert::ToString(messageInfo->get_Size()));
Console::WriteLine(u"==================================");
}
client->Dispose();
Download Emails from Exchange Public Folders
Exchange public folders allow storing shared messages across users.
Aspose.Email IEWSClient allows you to perform the following operations with these folders and messages stored in them:
- List public folders with ListPublicFolders()
- Browse subfolders recursively with ListSubFolders()
- List the messages of a public folder with ListMessagesFromPublicFolder(), download them and save them (e.g., as MSG files)
Note: Microsoft Exchange Server 2007 or later is required, as earlier versions do not support EWS.
The following code sample downloads the messages of all public folders and their subfolders and saves them as Outlook MSG files. The helper function processes one folder and calls itself for the subfolders:
static void SaveMessagesFromPublicFolder(SharedPtr<IEWSClient> client, SharedPtr<ExchangeFolderInfo> folder, int32_t& count)
{
Console::WriteLine(u"Folder Name: " + folder->get_DisplayName());
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessagesFromPublicFolder(folder))
{
SharedPtr<MailMessage> message = client->FetchMessage(messageInfo->get_UniqueUri());
Console::WriteLine(message->get_Subject());
message->Save(Convert::ToString(count++) + u"_public.msg", SaveOptions::get_DefaultMsgUnicode());
}
// Process the subfolders recursively
if (folder->get_ChildFolderCount() > 0)
{
for (SharedPtr<ExchangeFolderInfo> subfolder : client->ListSubFolders(folder))
{
SaveMessagesFromPublicFolder(client, subfolder, count);
}
}
}
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
try
{
int32_t count = 0;
for (SharedPtr<ExchangeFolderInfo> publicFolder : client->ListPublicFolders())
{
Console::WriteLine(u"Name: " + publicFolder->get_DisplayName());
Console::WriteLine(u"Subfolders count: " + Convert::ToString(publicFolder->get_ChildFolderCount()));
SaveMessagesFromPublicFolder(client, publicFolder, count);
}
}
catch (System::Exception& ex)
{
Console::WriteLine(ex->get_Message());
}
client->Dispose();
Move Messages Between Exchange Folders
You can move messages from one Exchange folder to another using the IEWSClient::MoveItem method. It takes:
- the unique URI of the message to move;
- the URI of the destination folder.
The following code sample moves the messages whose subject contains “process this message” from the Inbox to the Deleted Items folder.
- Connect to Exchange Server using EWS credentials.
- Get mailbox information (folder URIs).
- List all messages from the Inbox.
- Check if the subject of a message contains “process this message”.
- Move matching messages to the Deleted Items folder.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
SharedPtr<ExchangeMailboxInfo> mailboxInfo = client->GetMailboxInfo();
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(mailboxInfo->get_InboxUri()))
{
String subject = messageInfo->get_Subject();
if (!String::IsNullOrEmpty(subject) && subject.ToLower().Contains(u"process this message"))
{
client->MoveItem(messageInfo->get_UniqueUri(), mailboxInfo->get_DeletedItemsUri());
Console::WriteLine(u"Message moved: " + subject);
}
}
client->Dispose();
Delete Messages from an Exchange Folder
A message is deleted with IEWSClient::DeleteItem. It takes the message’s unique URI and the DeletionOptions: get_DeletePermanently() removes the message, get_MoveToDeletedItems() moves it to the Deleted Items folder.
The following code sample deletes the messages of the Inbox whose subject contains the word “delete”.
- Iterate through Inbox messages.
- Process messages based on some criteria (in this example, we find a keyword in the message subject).
- Delete matching messages.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
for (SharedPtr<ExchangeMessageInfo> messageInfo : client->ListMessages(client->get_MailboxInfo()->get_InboxUri()))
{
String subject = messageInfo->get_Subject();
if (!String::IsNullOrEmpty(subject) && subject.ToLower().Contains(u"delete"))
{
client->DeleteItem(messageInfo->get_UniqueUri(), DeletionOptions::get_DeletePermanently());
Console::WriteLine(u"Message deleted: " + subject);
}
}
client->Dispose();
Copy Messages to Another Exchange Folder
Use IEWSClient::CopyItem to duplicate a message into a different folder. The method returns the URI of the newly created copy.
The following code sample appends a message to the Inbox and copies it to the Deleted Items folder.
SharedPtr<IEWSClient> client = EWSClient::GetEWSClient(u"https://outlook.office365.com/ews/exchange.asmx", u"username", u"password");
try
{
SharedPtr<MailMessage> message = MakeObject<MailMessage>(u"from@domain.com", u"to@domain.com", u"Copy test", u"A message to copy");
String messageUri = client->AppendMessage(message);
String copyUri = client->CopyItem(messageUri, client->get_MailboxInfo()->get_DeletedItemsUri());
Console::WriteLine(u"Copy: " + copyUri);
}
catch (System::Exception& ex)
{
Console::WriteLine(ex->get_Message());
}
client->Dispose();