עבודה עם מצורפי TNEF

Transport Neutral Encapsulation Format (TNEF) הוא פורמט קבצים מצורפים קנייני שנמצא בשימוש ב‑Microsoft Outlook וב‑Exchange Server. מצורפים אלו כוללים לעיתים נתוני הודעה עשירים כגון טקסט מעוצב, תמונות מוטמעות או בקשות פגישות.

Aspose.Email עבור C++ מספקת תמיכה מלאה בקריאת ושמירת מצורפי TNEF בעת טעינת הודעות דוא"ל. ניתן לגשת ולשנות את תוכן מצורפי TNEF ואז לשמור את ההודעה בפורמט המקורי או בפורמט שונה תוך שמירה על כל הנתונים המוטמעים.

הדוגמאות במאמר זה משתמשות בכותרות ובמרחבי שם אלה:

#include <MailMessage.h>
#include <Attachment.h>
#include <AttachmentCollection.h>
#include <LinkedResource.h>
#include <LinkedResourceCollection.h>
#include <EmlLoadOptions.h>
#include <MsgLoadOptions.h>
#include <EmlSaveOptions.h>
#include <MsgSaveOptions.h>
#include <SaveOptions.h>
#include <MailMessageSaveType.h>
#include <FileCompatibilityMode.h>
#include <Mime/ContentType.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiAttachment.h>
#include <Mapi/MapiAttachmentCollection.h>
#include <Mapi/MailConversionOptions.h>
#include <system/io/file.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;

קריאת הודעות דוא"ל תוך שמירה על מצורפי TNEF

כאשר הודעת Outlook נטענת כ‑ MailMessage, MsgLoadOptions להחליט כיצד ייוצג תוכן Outlook הספציפי. עם PreserveTnefAttachments קובע ל true, התוכן נארז במקבץ TNEF יחיד, winmail.dat, בדיוק כפי ש‑Exchange ישלח את ההודעה; עם ברירת המחדל false, קבצי המצורפים של קובץ MSG הופכים לקבצים מצורפים MIME רגילים.

for (bool preserve : { true, false })
{
    SharedPtr<MsgLoadOptions> options = MakeObject<MsgLoadOptions>();
    options->set_PreserveTnefAttachments(preserve);
    SharedPtr<MailMessage> eml = MailMessage::Load(u"MsgWithAtt.msg", options);

    Console::WriteLine(u"PreserveTnefAttachments = " + Convert::ToString(preserve) + u":");
    for (SharedPtr<Attachment> attachment : eml->get_Attachments())
    {
        Console::WriteLine(u"   " + attachment->get_Name() + (attachment->get_IsTnef() ? u" (TNEF)" : u""));
    }
}

שמר או פענח את מכולת TNEF

הודעה שהתקבלה כ‑TNEF נושאת את כל הנתונים הספציפיים ל‑Outlook בחלק אחד winmail.dat חלק. עבור הודעה כזו, ה‑ PreserveTnefAttachments מאפיין של EmlLoadOptions קובע איך ההודעה תיראה לאחר הניתוח:

  • true - המכולה נשארת ללא שינוי ומופיעה כ‑ winmail.dat קובץ מצורף. השתמש בזה כאשר יש לכתוב את ההודעה חזרה באותו צורה;
  • false (ברירת המחדל) - המכולה מפוענחת והכל שהיא מחזיקה הופך לקובץ מצורף רגיל.
// keep the TNEF container as a single winmail.dat attachment
SharedPtr<EmlLoadOptions> preserve = MakeObject<EmlLoadOptions>();
preserve->set_PreserveTnefAttachments(true);
SharedPtr<MailMessage> kept = MailMessage::Load(u"tnefEml1.eml", preserve);

Console::WriteLine(u"With PreserveTnefAttachments = true");
for (SharedPtr<Attachment> attachment : kept->get_Attachments())
{
    Console::WriteLine(u"   " + attachment->get_Name());
}

// the default: decode the container and expose its content as regular attachments
SharedPtr<EmlLoadOptions> decode = MakeObject<EmlLoadOptions>();
decode->set_PreserveTnefAttachments(false);
SharedPtr<MailMessage> decoded = MailMessage::Load(u"tnefEml1.eml", decode);

Console::WriteLine(u"With PreserveTnefAttachments = false");
for (SharedPtr<Attachment> attachment : decoded->get_Attachments())
{
    Console::WriteLine(u"   " + attachment->get_Name());
}

המאפיין זה זמין ב‑ MsgLoadOptions ו MhtmlLoadOptions.

זיהוי הודעות וקבצים מצורפים TNEF

OriginalIsTnef מדווח האם ההודעה הטעונה הייתה TNEF, ו‑ Attachment::IsTnef האם קובץ מצורף מסוים הוא המכולה עצמה.

SharedPtr<MailMessage> mail = MailMessage::Load(u"tnefEml1.eml");

// whether the source message was a TNEF one
Console::WriteLine(u"Is the message originally TNEF? " + Convert::ToString(mail->get_OriginalIsTnef()));

// whether a particular attachment is a TNEF container
SharedPtr<EmlLoadOptions> options = MakeObject<EmlLoadOptions>();
options->set_PreserveTnefAttachments(true);
SharedPtr<MailMessage> preserved = MailMessage::Load(u"tnefEml1.eml", options);

for (SharedPtr<Attachment> attachment : preserved->get_Attachments())
{
    Console::WriteLine(attachment->get_Name() + u" - IsTnef: " + Convert::ToString(attachment->get_IsTnef()));
}

קריאה וכתיבה של קבצים מצורפים TNEF ישירות

קובץ מצורף MAPI ניתן לכתוב בצורת TNEF ולקרא חזרה עם SaveToTnef והמתודה הסטטית LoadFromTnef. שניהם פועלים עם שם קובץ ועם זרם, מה שמאפשר לייצר winmail.dat קובץ או להעביר עיצוב ספציפי של Outlook בין הודעות.

SharedPtr<MapiMessage> msg = MapiMessage::Load(u"MsgWithAtt.msg");

// write an attachment out in TNEF form and read it back
SharedPtr<IO::MemoryStream> stream = MakeObject<IO::MemoryStream>();
msg->get_Attachments()->idx_get(0)->SaveToTnef(stream);
stream->set_Position(0);

SharedPtr<MapiAttachment> fromStream = MapiAttachment::LoadFromTnef(stream);
msg->get_Attachments()->Add(fromStream->get_DisplayName(), fromStream->get_BinaryData());

// the same through a file
msg->get_Attachments()->idx_get(0)->SaveToTnef(u"attachment.dat");
SharedPtr<MapiAttachment> fromFile = MapiAttachment::LoadFromTnef(u"attachment.dat");

Console::WriteLine(u"Restored attachment: " + fromFile->get_DisplayName() +
    u", " + Convert::ToString(fromFile->get_BinaryData()->get_Length()) + u" bytes");

הוסף קובץ מצורף להודעת TNEF

קבצים מצורפים חדשים מתווספים להודעת TNEF כמו לכל הודעה אחרת. מה שחשוב הוא האופן שבו היא נשמרת: FileCompatibilityMode::PreserveTnefAttachments מציין EmlSaveOptions לשמור על חלק ה‑TNEF המקורי במקום לכתוב מחדש את ההודעה כ‑MIME פשוט.

SharedPtr<MailMessage> mailMessage = MailMessage::Load(u"tnefEml1.eml");

mailMessage->get_Attachments()->Add(MakeObject<Attachment>(IO::File::OpenRead(u"1.jpg"), u"1.jpg", u"image/jpeg"));

// FileCompatibilityMode keeps the TNEF part of the source message intact
SharedPtr<EmlSaveOptions> emlSaveOptions = MakeObject<EmlSaveOptions>(MailMessageSaveType::get_EmlFormat());
emlSaveOptions->set_FileCompatibilityMode(FileCompatibilityMode::PreserveTnefAttachments);

mailMessage->Save(u"TnefWithNewAttachment.eml", emlSaveOptions);

SharedPtr<MailMessage> reloaded = MailMessage::Load(u"TnefWithNewAttachment.eml");
Console::WriteLine(u"Attachments after saving: " + Convert::ToString(reloaded->get_Attachments()->get_Count()));

החלפת המשאבים של הודעת TNEF

התמונות של הודעת TNEF - כולל אלו של הודעות משובצות בתוכה - ניתן להחליף באחרות. העזר למטה עובר על הקבצים המצורפים באופן רקורסיבי: תמונות מוחלפות ישירות, הודעות משובצות מנתחות, מעובדות ונכתבות חזרה לתוכן הקובץ המצורף.

// Replaces the images of a message, descending into embedded messages
void UpdateResources(SharedPtr<MailMessage> msg, String imgFileName)
{
    for (SharedPtr<Attachment> attachment : msg->get_Attachments())
    {
        String mediaType = attachment->get_ContentType()->get_MediaType();
        String extension = IO::Path::GetExtension(attachment->get_Name()).ToLower();

        if (mediaType == u"image/png" || extension == u".jpg" || extension == u".png")
        {
            attachment->set_ContentStream(MakeObject<IO::MemoryStream>(IO::File::ReadAllBytes(imgFileName)));
        }
        else if (mediaType == u"message/rfc822" || extension == u".msg" || extension == u".eml")
        {
            SharedPtr<IO::MemoryStream> content = MakeObject<IO::MemoryStream>();
            attachment->Save(content);
            content->set_Position(0);

            SharedPtr<MailMessage> embedded = MailMessage::Load(content);
            UpdateResources(embedded, imgFileName);

            SharedPtr<IO::MemoryStream> updated = MakeObject<IO::MemoryStream>();
            embedded->Save(updated, SaveOptions::get_DefaultMsgUnicode());
            updated->set_Position(0);
            attachment->set_ContentStream(updated);
        }
    }

    for (SharedPtr<LinkedResource> resource : msg->get_LinkedResources())
    {
        if (resource->get_ContentType()->get_MediaType() == u"image/png")
        {
            resource->set_ContentStream(MakeObject<IO::MemoryStream>(IO::File::ReadAllBytes(imgFileName)));
        }
    }
}
SharedPtr<MailMessage> originalMailMessage = MailMessage::Load(u"tnefEml1.eml");

UpdateResources(originalMailMessage, u"1.jpg");

SharedPtr<EmlSaveOptions> emlSaveOptions = MakeObject<EmlSaveOptions>(MailMessageSaveType::get_EmlFormat());
emlSaveOptions->set_FileCompatibilityMode(FileCompatibilityMode::PreserveTnefAttachments);

originalMailMessage->Save(u"UpdatedTnefResources.eml", emlSaveOptions);

יצירת TNEF EML מקובץ MSG

ל‑Outlook הודעה עשויה לכלול טבלאות, גופנים ועיצובי RTF אחרים שהמרה פשוטה ל‑MIME לא יכולה לבטא. המרתה ל‑TNEF EML משמרת את העיצוב: לקוחות דואר שמבינים TNEF מציגים את ההודעה כפי ש‑Outlook עושה. קבע ConvertAsTnef על MailConversionOptions, או טען את ה‑MSG עם PreserveTnefAttachments הפעלה ושמירת התוצאה כ‑EML.

SharedPtr<MapiMessage> mapiMsg = MapiMessage::Load(u"MSG_file_with_RTF_Formatting.msg");

// the RTF formatting of the MSG survives the conversion inside a TNEF part
SharedPtr<MailConversionOptions> conversionOptions = MakeObject<MailConversionOptions>();
conversionOptions->set_ConvertAsTnef(true);

SharedPtr<MailMessage> message = mapiMsg->ToMailMessage(conversionOptions);
message->Save(u"TnefFromMsg.eml", SaveOptions::get_DefaultEml());

// the same result can be reached through the load options
SharedPtr<MsgLoadOptions> loadOptions = MakeObject<MsgLoadOptions>();
loadOptions->set_PreserveTnefAttachments(true);
SharedPtr<MailMessage> eml = MailMessage::Load(u"MSG_file_with_RTF_Formatting.msg", loadOptions);
eml->Save(u"TnefFromMsg2.eml", SaveOptions::get_DefaultEml());

Console::WriteLine(u"Originally TNEF: " + Convert::ToString(MailMessage::Load(u"TnefFromMsg.eml")->get_OriginalIsTnef()));