TNEF 첨부 파일 작업

**Transport Neutral Encapsulation Format (TNEF)**은 Microsoft Outlook 및 Exchange Server에서 사용하는 독점적인 이메일 첨부 형식입니다. 이러한 첨부 파일에는 서식이 지정된 텍스트, 포함된 이미지, 회의 요청과 같은 풍부한 메시지 데이터가 포함되는 경우가 많습니다.

Aspose.Email for 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 전용 콘텐츠가 어떻게 표시될지 결정합니다. With PreserveTnefAttachments set to 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);

MSG 파일에서 TNEF EML 만들기

Outlook 메시지는 표, 글꼴 및 기타 RTF 서식을 포함할 수 있는데 일반 MIME 변환으로는 표현할 수 없습니다. 이를 TNEF EML로 변환하면 그 서식이 유지됩니다: TNEF를 지원하는 메일 클라이언트는 Outlook과 동일하게 메시지를 표시합니다. 설정 ConvertAsTnef on 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()));