Outlook MSG 파일에서 첨부 파일 관리

**Aspose.Email for C++**은 Microsoft Outlook MSG 파일 작업 시 첨부 파일에 접근, 저장, 제거 및 포함을 위한 풍부한 API를 제공합니다. 첨부 파일은 다음을 통해 처리됩니다: 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 그 ID를 반환하고, 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) - 참조 첨부 파일을 추가합니다.

다음 코드 예제는 일반 첨부 파일과 임베디드 메시지를 추가하고 display name을 변경합니다. 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");