Управление вложениями в Outlook MSG‑файлах
Aspose.Email for C++ предоставляет обширный API для доступа, сохранения, удаления и внедрения вложений при работе с файлами Microsoft Outlook MSG. Вложениями управляют через MapiMessage класс, используя его Attachments свойство, которое раскрывает MapiAttachmentCollection.
Примеры в этой статье используют следующие заголовки и пространства имён:
#include <MailMessage.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <Mapi/MapiObjectProperty.h>
#include <Mapi/MapiPropertyCollection.h>
#include <Mapi/MailConversionOptions.h>
#include <Mapi/ReferenceAttachmentOptions.h>
#include <Mapi/InlineAttachmentExtractor.h>
#include <system/io/file.h>
#include <system/io/directory.h>
#include <system/io/path.h>
#include <system/io/memory_stream.h>
#include <system/convert.h>
using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
Сохранение вложений из MSG‑файла
Для извлечения и сохранения вложений из MSG‑файла:
- Загрузить сообщение с помощью MapiMessage::Load.
- Итерируйтесь по MapiAttachmentCollection возвращённый
get_Attachments. - Сохраните каждое вложение, используя MapiAttachment::Save() метод.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"MsgWithAtt.msg");
IO::Directory::CreateDirectory_(u"SavedAttachments");
for (SharedPtr<MapiAttachment> attachment : message->get_Attachments())
{
String path = IO::Path::Combine(u"SavedAttachments", attachment->get_LongFileName());
attachment->Save(path);
Console::WriteLine(u"Saved " + path);
}
Удалить вложения
Aspose.Email для C++ предоставляет два статических метода, которые удаляют вложения из файла сообщения без его открытия в вашем коде:
- RemoveAttachments принимает путь к файлу сообщения, разбирает сообщение и удаляет из него все вложения. Возвращает удалённые вложения.
- DestroyAttachments делает то же без полного разбора файла MSG, что делает его быстрее.
Оба метода изменяют файл на месте, поэтому пример работает с копиями.
IO::File::Copy(u"MsgWithAtt.msg", u"ToRemove.msg", true);
IO::File::Copy(u"MsgWithAtt.msg", u"ToDestroy.msg", true);
// parses the file and returns the attachments it removed
SharedPtr<MapiAttachmentCollection> removed = MapiMessage::RemoveAttachments(u"ToRemove.msg");
Console::WriteLine(u"Removed: " + Convert::ToString(removed->get_Count()));
// does the same without parsing the message, which is faster
MapiMessage::DestroyAttachments(u"ToDestroy.msg");
Console::WriteLine(u"Attachments left: " +
Convert::ToString(MapiMessage::Load(u"ToRemove.msg")->get_Attachments()->get_Count()) + u" / " +
Convert::ToString(MapiMessage::Load(u"ToDestroy.msg")->get_Attachments()->get_Count()));
Добавление вложений MSG
Файлы MSG могут содержать другие файлы MSG как стандартные или встроенные вложения. Перегрузка MapiAttachmentCollection::Add который принимает MapiMessage встраивает сообщение Outlook; затем Outlook открывает вложение как сообщение, а не как файл.
Следующий пример кода создает новое сообщение, прикрепляет к нему существующий файл MSG как встроенное сообщение и сохраняет результат.
SharedPtr<MapiMessage> message = MakeObject<MapiMessage>(u"from@test.com", u"to@test.com", u"Subj", u"This is a message body");
SharedPtr<MapiMessage> attachMsg = MapiMessage::Load(u"Message.msg");
message->get_Attachments()->Add(u"Weekly report.msg", attachMsg);
message->Save(u"WithEmbeddedMsg_out.msg");
SharedPtr<MapiAttachment> attachment = MapiMessage::Load(u"WithEmbeddedMsg_out.msg")->get_Attachments()->idx_get(0);
Console::WriteLine(attachment->get_DisplayName() + u" is an Outlook message: " + Convert::ToString(attachment->get_ObjectData()->get_IsOutlookMessage()));
Различение типов вложений
Outlook хранит каждое вложение сообщения в Вложения коллекция, но они не все одного типа. IsInline отмечает файлы, которые тело отображает непосредственно — в основном изображения, и IsReference те, которые являются лишь ссылкой на файл, хранящийся где‑то ещё.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"messageWithEmbeddedEML.msg");
for (SharedPtr<MapiAttachment> attach : message->get_Attachments())
{
Console::WriteLine(attach->get_DisplayName() +
u" | inline: " + Convert::ToString(attach->get_IsInline()) +
u" | reference: " + Convert::ToString(attach->get_IsReference()) +
u" | file name: " + attach->get_LongFileName());
}
Добавление файлов, сообщений и ссылок
MapiAttachmentCollection::Add имеет перегрузку для каждого типа вложения: массив байт становится обычным файлом, MapiMessage становится встроенным сообщением, и ReferenceAttachmentOptions объект генерирует ссылку на файл в облачном хранилище — общую ссылку, расположение файла и название провайдера.
SharedPtr<MapiMessage> message = MakeObject<MapiMessage>(u"from@test.com", u"to@test.com",
u"Subj", u"This is a message body");
// a regular attachment from a byte array
message->get_Attachments()->Add(u"note.txt", IO::File::ReadAllBytes(u"description.html"));
// another Outlook message, embedded as an attachment
SharedPtr<MapiMessage> attachMsg = MapiMessage::Load(u"Message.msg");
message->get_Attachments()->Add(u"Weekly report.msg", attachMsg);
// a reference attachment: the file stays in the cloud storage
SharedPtr<ReferenceAttachmentOptions> options = MakeObject<ReferenceAttachmentOptions>(
u"https://drive.google.com/file/d/1HJ-M3F2qq1oRrTZ2GZhUdErJNy2CT3DF/",
u"https://drive.google.com/drive/my-drive",
u"GoogleDrive");
message->get_Attachments()->Add(u"Document.pdf", options);
message->Save(u"WithAttachments.msg");
Console::WriteLine(u"Attachments: " + Convert::ToString(message->get_Attachments()->get_Count()));
Чтение встроенного сообщения
Содержимое встроенного сообщения доступно через ObjectData. IsOutlookMessage определяет, действительно ли объект является сообщением, ToMapiMessage возвращает его и MapiMessage::FromProperties воссоздаёт его из сырой коллекции свойств, когда нужно выполнить дальнейшее преобразование.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"WithEmbeddedMsg.msg");
SharedPtr<MapiAttachment> attachment = message->get_Attachments()->idx_get(0);
if (attachment->get_ObjectData() != nullptr && attachment->get_ObjectData()->get_IsOutlookMessage())
{
// the embedded item as a MapiMessage
SharedPtr<MapiMessage> embedded = attachment->get_ObjectData()->ToMapiMessage();
Console::WriteLine(u"Embedded subject: " + embedded->get_Subject());
// the same item built from its properties and converted to MIME
SharedPtr<MapiMessage> fromProperties = MapiMessage::FromProperties(attachment->get_ObjectData()->get_Properties());
SharedPtr<MailMessage> eml = fromProperties->ToMailMessage(MakeObject<MailConversionOptions>());
eml->Save(u"NestedMailMessage.eml", SaveOptions::get_DefaultEml());
}
Вставка, замена и переименование вложений
Помимо добавления, коллекция может поместить сообщение в выбранную позицию с помощью Insert и перезаписать существующую запись с помощью Заменить содержимое встроенного вложения MSG. Имя, отображаемое в Outlook, является записываемым Отображаемое имя свойство.
SharedPtr<MapiMessage> message = MapiMessage::Load(u"WithAttachments.msg");
// take one of the embedded messages out
SharedPtr<IO::MemoryStream> memoryStream = MakeObject<IO::MemoryStream>();
message->get_Attachments()->idx_get(1)->Save(memoryStream);
memoryStream->set_Position(0);
SharedPtr<MapiMessage> extracted = MapiMessage::Load(memoryStream);
// put it back at a chosen position
message->get_Attachments()->Insert(1, u"inserted.msg", extracted);
// or overwrite the attachment that is already there
message->get_Attachments()->Replace(1, u"replaced.msg", extracted);
// the display name can be changed afterwards
message->get_Attachments()->idx_get(0)->set_DisplayName(u"New display name");
message->Save(u"RearrangedAttachments.msg");
for (SharedPtr<MapiAttachment> attach : MapiMessage::Load(u"RearrangedAttachments.msg")->get_Attachments())
{
Console::WriteLine(attach->get_DisplayName());
}
Replace перезаписывает существующую запись; нельзя создать запись по индексу за пределами коллекции.
Извлечение OLE‑объектов из oledata.mso
Когда тело сообщения HTML, а не RTF, Outlook не сохраняет OLE‑объекты как отдельные вложения: они упаковываются в один oledata.mso вложение. InlineAttachmentExtractor::EnumerateMsoPackage разбивает этот пакет на отдельные OLE‑элементы. Каждый элемент — Microsoft Compound Document; чтение самого документа обычно делается для извлечения его CONTENTS stream — это задача библиотеки compound‑file, которую Aspose.Email не включает.
SharedPtr<MapiMessage> msg = MapiMessage::Load(u"messageWithEmbeddedEML.msg");
for (SharedPtr<MapiAttachment> attachment : msg->get_Attachments())
{
if (attachment->get_LongFileName() == u"oledata.mso")
{
// every entry is one OLE package in Compound File format
auto packages = InlineAttachmentExtractor::EnumerateMsoPackage(
MakeObject<IO::MemoryStream>(attachment->get_BinaryData()));
for (auto package : packages)
{
Console::WriteLine(package.get_Key() + u": " +
Convert::ToString(package.get_Value()->get_Length()) + u" bytes");
// hand the bytes to a library that reads Compound File documents
IO::File::WriteAllBytes(package.get_Key(), package.get_Value());
}
}
}
Доступ к только что добавленному вложению
Этот Добавить методы MapiAttachmentCollection class return the MapiAttachment object they create. This gives you immediate access to the new attachment, so you can configure it right after insertion without searching the collection for it. The following overloads return the created attachment:
Add(String name, ArrayPtr<uint8_t> data)- добавляет обычное вложение из массива байт.Add(String name, SharedPtr<MapiMessage> msg)- добавляет сообщение Outlook как встроенное вложение.Add(String name, SharedPtr<ReferenceAttachmentOptions> options)- добавляет ссылочное вложение.
Следующий пример кода добавляет обычное вложение и встроенное сообщение и изменяет их отображаемые имена с помощью set_DisplayName():
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <system/io/file.h>
using namespace System;
using namespace Aspose::Email::Mapi;
auto message = MakeObject<MapiMessage>(u"from@domain.com", u"to@domain.com", u"Weekly report", u"Please find the files attached.");
// Add a regular attachment and change its display name
SharedPtr<MapiAttachment> attachment = message->get_Attachments()->Add(u"invoice.pdf", IO::File::ReadAllBytes(u"invoice.pdf"));
attachment->set_DisplayName(u"Invoice #2026-001.pdf");
// Add an embedded message and change its display name
SharedPtr<MapiAttachment> embedded = message->get_Attachments()->Add(u"original.msg", MapiMessage::Load(u"message.msg"));
embedded->set_DisplayName(u"Original request");
message->Save(u"report.msg");