Reading and Extracting OLM Messages

Once a folder has been located, its messages can be listed as lightweight summaries or as complete MapiMessage objects, filtered with a query, and extracted individually. This article covers each of these operations and ends with the fault-tolerant traversal used for damaged files.

The samples below use the following headers and namespaces:

#include <Storage/Olm/OlmStorage.h>
#include <Storage/Olm/OlmFolder.h>
#include <Storage/Olm/OlmMessageInfo.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiElectronicAddress.h>
#include <Tools/Search/MailQueryBuilder.h>
#include <Tools/Search/MailQuery.h>
#include <Tools/Search/StringComparisonField.h>
#include <Tools/Search/DateComparisonField.h>
#include <Exceptions/TraversalExceptionsCallback.h>
#include <Exceptions/TraversalAsposeException.h>
#include <system/collections/list_ext.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::Storage::Olm;
using namespace Aspose::Email::Tools::Search;
using namespace Aspose::Email::Exceptions;

List the Messages of a Folder

OlmFolder offers two enumerators:

Summaries first:

SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

for (SharedPtr<OlmMessageInfo> messageInfo : folder->EnumerateMessages())
{
    Console::WriteLine(messageInfo->get_Subject());
}

olm->Dispose();

Full messages, saved to disk as they are enumerated:

SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

int index = 0;
for (SharedPtr<MapiMessage> msg : folder->EnumerateMapiMessages())
{
    // every item arrives fully loaded, so it can be saved straight away
    msg->Save(String::Format(u"inbox_{0}.msg", index++));
}

olm->Dispose();

Read Message Summaries

An OlmMessageInfo object is filled from the index of the archive, so reading its properties costs almost nothing:

Property Meaning
Subject Subject line.
From Sender as a MapiElectronicAddress; may be nullptr.
To List of recipient addresses.
Date Date of the message.
ModifiedDate Last modification time.
HasAttachments Whether attachments are present.
MessageClass MAPI message class, e.g. IPM.Note.
EntryId Identifier used to extract the message later.
SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

for (SharedPtr<OlmMessageInfo> messageInfo : folder->EnumerateMessages())
{
    Console::WriteLine(u"Subject: " + messageInfo->get_Subject());

    if (messageInfo->get_From() != nullptr)
    {
        Console::WriteLine(u"From: " + messageInfo->get_From()->get_EmailAddress());
    }

    for (SharedPtr<MapiElectronicAddress> recipient : messageInfo->get_To())
    {
        Console::WriteLine(u"To: " + recipient->get_EmailAddress());
    }

    Console::WriteLine(u"Date: " + messageInfo->get_Date().ToString());
    Console::WriteLine(u"Modified: " + messageInfo->get_ModifiedDate().ToString());
    Console::WriteLine(u"Has attachments: " + Convert::ToString(messageInfo->get_HasAttachments()));
    Console::WriteLine(u"Message class: " + messageInfo->get_MessageClass());
    Console::WriteLine(String(u'-', 30));
}

olm->Dispose();

Filter Messages with a Query

Instead of examining every summary in code, describe the wanted messages with a MailQueryBuilder and pass the resulting MailQuery to the EnumerateMessages(query) overload. The example keeps the messages received during the last seven years whose subject contains the word “test”:

SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

// Only messages received during the last 7 years whose subject contains "test"
SharedPtr<MailQueryBuilder> builder = MakeObject<MailQueryBuilder>();
builder->get_InternalDate()->Since(DateTime::get_Now().AddYears(-7));
builder->get_Subject()->Contains(u"test");
SharedPtr<MailQuery> query = builder->GetQuery();

for (SharedPtr<OlmMessageInfo> messageInfo : folder->EnumerateMessages(query))
{
    Console::WriteLine(messageInfo->get_Subject());
}

olm->Dispose();

Extract a Message as a MapiMessage

A typical pattern is to scan a folder through its summaries, apply a condition, and load only the items that pass. OlmStorage::ExtractMapiMessage accepts an OlmMessageInfo and returns the complete message. The example extracts only the messages that carry attachments:

SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

int index = 0;
for (SharedPtr<OlmMessageInfo> messageInfo : folder->EnumerateMessages())
{
    // pick only the messages that have attachments, then load them in full
    if (messageInfo->get_HasAttachments())
    {
        SharedPtr<MapiMessage> msg = olm->ExtractMapiMessage(messageInfo);
        msg->Save(String::Format(u"with_attachments_{0}.msg", index++));
    }
}

olm->Dispose();

Extract by Identifier

The EntryId string is stable for the lifetime of the file, so an application can store it and later call the ExtractMapiMessage(id) overload without enumerating the folder again:

SharedPtr<OlmStorage> olm = OlmStorage::FromFile(u"SampleOLM.olm");
SharedPtr<OlmFolder> folder = olm->GetFolder(u"Inbox", true);

for (SharedPtr<OlmMessageInfo> messageInfo : folder->EnumerateMessages())
{
    // the identifier can be persisted and used later without rescanning the folder
    String entryId = messageInfo->get_EntryId();

    SharedPtr<MapiMessage> msg = olm->ExtractMapiMessage(entryId);
    Console::WriteLine(msg->get_Subject());
}

olm->Dispose();

Extract Items with the Traversal API

For an archive that may be partially corrupted, combine the callback constructor described in Opening OLM Files with the storage-level EnumerateMessages(folder) method. That overload reports unreadable items to the callback and continues with the next one instead of throwing. The procedure is:

  1. Create the OlmStorage with a TraversalExceptionsCallback.
  2. Call Load; stop if it returns false.
  3. Get the folder tree with GetFolders.
  4. For every folder that HasMessages, enumerate its items through the storage and process them; then recurse into the sub-folders.
void ExtractItems(SharedPtr<OlmStorage> olm, SharedPtr<Collections::Generic::ListExt<SharedPtr<OlmFolder>>> folders)
{
    for (SharedPtr<OlmFolder> folder : folders)
    {
        if (folder->get_HasMessages())
        {
            Console::WriteLine(folder->get_Path());

            // the storage-level overload keeps going when a damaged item is met
            for (SharedPtr<MapiMessage> msg : olm->EnumerateMessages(folder))
            {
                Console::WriteLine(u"  " + msg->get_Subject());
            }
        }

        ExtractItems(olm, folder->get_SubFolders());
    }
}
TraversalExceptionsCallback callback = std::function<void(TraversalAsposeException, String)>(
    [](TraversalAsposeException exception, String id)
{
    // log the failure and carry on
    Console::WriteLine(u"Skipped item '" + id + u"': " + exception->get_Message());
});

SharedPtr<OlmStorage> olm = MakeObject<OlmStorage>(callback);

if (olm->Load(u"SampleOLM.olm"))
{
    ExtractItems(olm, olm->GetFolders());
}

olm->Dispose();