Writing MBOX Files

Creating an MBOX archive from scratch, or adding messages to one that Thunderbird already uses, is done with the MboxrdStorageWriter class. The writer takes ordinary MailMessage objects, so anything you can build or load with Aspose.Email - an EML file, an MSG converted to MIME, a message assembled in code - can be placed into the storage.

The sample below uses the following headers and namespaces:

#include <MailMessage.h>
#include <Storage/Mbox/MboxrdStorageWriter.h>
#include <Storage/Mbox/MboxSaveOptions.h>
#include <system/io/file_stream.h>
#include <system/guid.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Storage::Mbox;

Append Messages to a Storage File

The steps are:

  1. Open the target file with read/write access. FileMode::OpenOrCreate lets the same code start a new archive or extend an existing one.
  2. Construct an MboxrdStorageWriter over the stream, passing an MboxSaveOptions instance.
  3. Build the message and hand it to WriteMessage.
  4. Dispose the writer and close the stream so that the trailing data is flushed.
// Open (or create) the storage file for writing
SharedPtr<IO::FileStream> stream = MakeObject<IO::FileStream>(u"NewMailbox.mbox", IO::FileMode::OpenOrCreate, IO::FileAccess::ReadWrite);

// Initialize the writer over the stream
SharedPtr<MboxrdStorageWriter> writer = MakeObject<MboxrdStorageWriter>(stream, MakeObject<MboxSaveOptions>());

// Prepare a message
SharedPtr<MailMessage> message = MakeObject<MailMessage>(u"from@domain.com", u"to@domain.com",
    Guid::NewGuid().ToString(), u"added from Aspose.Email for C++");
message->set_IsDraft(false);

// Append the message to the storage
writer->WriteMessage(message);

// Release the writer and the stream
writer->Dispose();
stream->Close();

A file name can be passed instead of a stream - MakeObject<MboxrdStorageWriter>(u"NewMailbox.mbox", options) - in which case the writer opens and closes the file itself. To add several messages, call WriteMessage repeatedly on the same writer; each call appends one message and returns a string identifier for it.