ניהול קבצים מצורפים בקבצי 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 עבור 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());
}

חילוץ עצמים OLE מ‑oledata.mso

כאשר גוף הודעה הוא HTML במקום RTF, Outlook אינו מאחסן את עצמים OLE שלו כקבצים מצורפים נפרדים: הם נארזים כולם באחד oledata.mso קובץ מצורף. InlineAttachmentExtractor::EnumerateMsoPackage מפצלת את החבילה לפריטים OLE פרטיים. כל פריט הוא Microsoft Compound Document; קריאת המסמך עצמו - בדרך כלל כדי לשאוב את CONTENTS זרם - זהו תפקיד של ספריית קובץ מרוכב, שאינה נכללת ב‑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");