管理 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 文件提取并保存附件:

  1. 使用以下方式加载邮件 MapiMessage::Load.
  2. 遍历 MapiAttachmentCollection 由 get_Attachments.
  3. 使用以下方法保存每个附件 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 for 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 并用以下方式覆盖现有条目 替换。在 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());
}

从 oledata.mso 中提取 OLE 对象

当消息正文为 HTML 而非 RTF 时,Outlook 不会将其 OLE 对象存储为单独的附件:它们会被打包在一个 oledata.mso 附件。 InlineAttachmentExtractor::EnumerateMsoPackage 将该包拆分为单个 OLE 项目。每个项目都是 Microsoft 复合文档;读取文档本身——通常是为了提取其 CONTENTS stream —— 这需要复合文件库,而 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 类返回 MapiAttachment 对象它们创建。这让您立即访问新附件,因而可以在插入后立即配置它,而无需在集合中搜索。以下重载返回创建的附件:

  • 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");