写入 MBOX 文件
Contents
[
Hide
]
从头创建 MBOX 归档,或向 Thunderbird 已使用的归档添加消息,都使用 MboxrdStorageWriter 类。写入器接受普通的 MailMessage 对象,因此您可以构建或加载的任何 Aspose.Email 内容——EML 文件、转换为 MIME 的 MSG、代码组装的消息——都可以放入存储中。
下面的示例使用以下头文件和命名空间:
#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;
将消息追加到存储文件
步骤如下:
- 以读写访问方式打开目标文件。
FileMode::OpenOrCreate让相同的代码可以创建新的归档或扩展已有的归档。 - 构造一个 MboxrdStorageWriter 通过流传递一个 MboxSaveOptions 实例。
- 构建消息并交给 WriteMessage.
- 释放写入器并关闭流,以便冲刷尾部数据。
// 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();
使用
FileAccess::ReadWrite,而不是 FileAccess::Write:写入器在追加之前需要读取文件的现有内容,而只写流会导致其因 NotSupportedException.
可以传递文件名而不是流—— MakeObject<MboxrdStorageWriter>(u"NewMailbox.mbox", options) - 在这种情况下写入器自行打开并关闭文件。要添加多条消息,请调用 WriteMessage 在同一写入器上重复调用;每次调用追加一条消息并返回其字符串标识符。