Quản lý Tệp Đính Kèm trong Tệp Outlook MSG

Aspose.Email for C++ cung cấp API phong phú để truy cập, lưu, xóa và nhúng tệp đính kèm khi làm việc với các tệp Microsoft Outlook MSG. Các tệp đính kèm được xử lý thông qua MapiMessage lớp, sử dụng Attachments thuộc tính, cung cấp một MapiAttachmentCollection.

Các mẫu trong bài viết này sử dụng các tiêu đề và không gian tên sau:

#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;

Lưu Tệp Đính Kèm từ Tệp MSG

Để trích xuất và lưu tệp đính kèm từ một tệp MSG:

  1. Tải tin nhắn bằng cách sử dụng MapiMessage::Load.
  2. Lặp qua MapiAttachmentCollection được trả về bởi get_Attachments.
  3. Lưu mỗi tệp đính kèm bằng cách sử dụng MapiAttachment::Save() phương thức.
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);
}

Xóa Đính kèm

Aspose.Email for C++ cung cấp hai phương thức tĩnh loại bỏ các tệp đính kèm của một tệp tin nhắn mà không cần mở nó trong mã của bạn:

  • RemoveAttachments nhận đường dẫn của tệp tin tin nhắn, phân tích tin nhắn và loại bỏ mọi tệp đính kèm khỏi nó. Nó trả về các tệp đính kèm đã bị xóa.
  • DestroyAttachments thực hiện cùng việc mà không cần phân tích đầy đủ tệp MSG, giúp nhanh hơn.

Cả hai phương pháp đều thay đổi tệp tại chỗ, vì vậy mẫu hoạt động trên các bản sao.

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()));

Thêm Đính kèm MSG

Các tệp MSG có thể chứa các tệp MSG khác dưới dạng tệp đính kèm tiêu chuẩn hoặc nhúng. Overload của MapiAttachmentCollection::Add mà nhận một MapiMessage nhúng một tin nhắn Outlook; Outlook sau đó mở tệp đính kèm như một tin nhắn thay vì như một tệp.

Mã mẫu sau tạo một tin nhắn mới, đính kèm một tệp MSG hiện có dưới dạng tin nhắn nhúng và lưu kết quả.

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()));

Phân biệt Các Loại Đính Kèm

Outlook lưu mọi tệp đính kèm của một tin nhắn trong Tệp Đính Kèm bộ sưu tập, nhưng chúng không phải cùng một loại. IsInline đánh dấu các tệp mà phần thân hiển thị tại chỗ - chủ yếu là hình ảnh - và IsReference những tệp chỉ là liên kết tới tệp được lưu ở nơi khác.

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());
}

Thêm Tệp, Tin Nhắn và Tham Chiếu

MapiAttachmentCollection::Add có một overload cho mỗi loại tệp đính kèm: một mảng byte trở thành tệp thường, một MapiMessage trở thành một tin nhắn nhúng, và một ReferenceAttachmentOptions đối tượng tạo ra một liên kết tới tệp trong lưu trữ đám mây - liên kết chia sẻ, vị trí của tệp và tên nhà cung cấp.

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()));

Đọc Tin Nhắn Nhúng

Nội dung của tin nhắn được nhúng được hiển thị qua ObjectData. IsOutlookMessage cho biết đối tượng thực sự là một tin nhắn hay không, ToMapiMessage trả về nó, và MapiMessage::FromProperties tái tạo nó từ bộ sưu tập thuộc tính thô khi bạn cần chuyển đổi thêm.

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());
}

Chèn, Thay thế và Đổi tên Tệp Đính Kèm

Ngoài việc nối, bộ sưu tập có thể đặt một tin nhắn ở vị trí đã chọn bằng Insert và ghi đè một mục hiện có bằng Thay Thế. Tên hiển thị trong Outlook là Tên hiển thị thuộc tính.

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());
}

Trích xuất Đối tượng OLE từ oledata.mso

Khi phần thân của tin nhắn là HTML thay vì RTF, Outlook không lưu các đối tượng OLE của nó như các tệp đính kèm riêng biệt: chúng cuối cùng được đóng gói trong một oledata.mso đính kèm. InlineAttachmentExtractor::EnumerateMsoPackage phân tách gói đó thành các mục OLE riêng lẻ. Mỗi mục là một Tài liệu Hợp chất Microsoft; đọc tài liệu đó - thường để trích xuất nội dung của nó CONTENTS luồng - là công việc cho một thư viện tệp hợp chất, mà Aspose.Email không bao gồm.

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());
        }
    }
}

Truy cập một Tệp Đính Kèm Mới Thêm

Cái Thêm phương thức của MapiAttachmentCollection lớp trả về MapiAttachment đối tượng chúng tạo. Điều này cho phép bạn truy cập ngay lập tức vào tệp đính kèm mới, để bạn có thể cấu hình nó ngay sau khi chèn mà không cần tìm kiếm trong bộ sưu tập. Các overload sau trả về tệp đính kèm đã tạo:

  • Add(String name, ArrayPtr<uint8_t> data) - thêm một tệp đính kèm thường từ một mảng byte.
  • Add(String name, SharedPtr<MapiMessage> msg) - thêm một tin nhắn Outlook dưới dạng tệp đính kèm nhúng.
  • Add(String name, SharedPtr<ReferenceAttachmentOptions> options) - thêm một tệp đính kèm tham chiếu.

Mã mẫu sau thêm một tệp đính kèm thường và một tin nhắn nhúng và thay đổi tên hiển thị của chúng bằng 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");