이메일 메시지 고급 관리

이 문서는 메시지 작성 및 저장을 넘어서는 기능을 모아둔 것입니다: 메시지 렌더링 제어, 스팸 필터링, MIME 구조의 숨겨진 부분 읽기, 메시지 읽음 여부 추적 등.

아래 샘플은 이러한 헤더와 네임스페이스를 사용합니다:

#include <MailMessage.h>
#include <MailAddressCollection.h>
#include <SaveOptions.h>
#include <EmlSaveOptions.h>
#include <MhtSaveOptions.h>
#include <MhtFormatOptions.h>
#include <MhtTemplateName.h>
#include <system/collections/list_ext.h>
#include <system/collections/specialized/string_dictionary.h>
#include <Common/Transform/HtmlToTextConverter.h>
#include <AntiSpam/SpamAnalyzer.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/MapiConversionOptions.h>
#include <system/io/directory.h>
#include <system/io/path.h>
#include <system/convert.h>

using namespace System;
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
using namespace Aspose::Email::AntiSpam;

커스텀 스타일로 하이퍼링크 렌더링

GetHtmlBodyText HTML 본문을 평문 텍스트로 변환합니다. 두 번째 오버로드는 HyperlinkRenderingCallback - 모든 링크의 전체 마크업을 받아 교체 텍스트를 반환하는 대리자입니다. 여기서 링크 주소를 유지할지, 어떻게 장식할지, 혹은 완전히 사라지게 할지를 결정합니다.

// Receives the <a ...>text</a> markup of every link and returns its replacement
String RenderHyperlinkWithHref(String source)
{
    int32_t start = source.IndexOf(u"href=\"") + 6;
    int32_t end = source.IndexOf(u"\"", start);
    String href = source.Substring(start, end - start);

    start = source.IndexOf(u">") + 1;
    end = source.IndexOf(u"<", start);
    String text = source.Substring(start, end - start);

    return String::Format(u"{0}<{1}>", text, href);
}

// Keeps only the visible text of the link
String RenderHyperlinkWithoutHref(String source)
{
    int32_t start = source.IndexOf(u">") + 1;
    int32_t end = source.IndexOf(u"<", start);
    return source.Substring(start, end - start);
}
SharedPtr<MailMessage> msg = MailMessage::Load(u"LinksSample.eml");

Console::WriteLine(msg->GetHtmlBodyText(Common::Transform::HyperlinkRenderingCallback(&RenderHyperlinkWithHref)));
Console::WriteLine(msg->GetHtmlBodyText(Common::Transform::HyperlinkRenderingCallback(&RenderHyperlinkWithoutHref)));

첫 번째 콜백은 <a href="https://www.aspose.com/">Aspose.Email</a> into Aspose.Email<https://www.aspose.com/>, 두 번째는 Aspose.Email.

MHTML에 표시할 헤더 선택

메시지를 MHTML 로 내보내면 라이브러리가 본문 위에 헤더 라인 블록을 작성합니다. RenderingHeaders 의 MhtSaveOptions 어떤 라인이 어떤 순서로 표시될지 결정합니다; 이름은 MhtTemplateName 클래스. 빈 컬렉션은 기본 블록을 의미합니다.

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

SharedPtr<MhtSaveOptions> options = SaveOptions::get_DefaultMhtml();

// the default header block
eml->Save(u"MhtDefaultOrder.mhtml", options);

// only these headers, in this order
options->get_RenderingHeaders()->Add(MhtTemplateName::From);
options->get_RenderingHeaders()->Add(MhtTemplateName::Subject);
options->get_RenderingHeaders()->Add(MhtTemplateName::To);
options->get_RenderingHeaders()->Add(MhtTemplateName::Sent);
eml->Save(u"MhtCustomOrder.mhtml", options);

// a different selection
options->get_RenderingHeaders()->Clear();
options->get_RenderingHeaders()->Add(MhtTemplateName::Attachments);
options->get_RenderingHeaders()->Add(MhtTemplateName::Cc);
options->get_RenderingHeaders()->Add(MhtTemplateName::Subject);
eml->Save(u"MhtAttachmentsFirst.mhtml", options);

모든 헤더를 출력에 기록

위 블록은 독자를 위한 요약입니다. 전체 MIME 헤더를 MHTML 파일에 넣으려면 전환하십시오 SaveAllHeaders 에.

SharedPtr<MailMessage> eml = MailMessage::Load(u"email-headers.eml");

SharedPtr<MhtSaveOptions> options = SaveOptions::get_DefaultMhtml();
options->set_SaveAllHeaders(true);

eml->Save(u"AllHeaders.mhtml", options);

캘린더 이벤트 렌더링

MHTML 로 저장된 회의는 다음과 같이 세부 정보를 표시합니다 MhtFormatOptions 두 가지를 모두 포함합니다 RenderCalendarEvent 및 WriteHeader:

SharedPtr<MailMessage> eml = MailMessage::Load(u"Test_Meeting.msg");

SharedPtr<MhtSaveOptions> options = MakeObject<MhtSaveOptions>();
options->set_MhtFormatOptions(MhtFormatOptions::RenderCalendarEvent | MhtFormatOptions::WriteHeader);

eml->Save(u"MeetingWithAttendees.mhtml", options);

해당 블록의 개별 라인은 다음을 통해 포맷됩니다 FormatTemplates, 동일한 MhtTemplateName 상수; 키에 빈 문자열을 할당하면 해당 라인이 출력에서 제거됩니다.

베이즈 스팸 분석기로 메시지 점수 매기기

SpamAnalyzer 베이즈 필터를 구현합니다. 먼저 이미 분류한 메시지로 학습합니다: TrainFilter 메시지와 스팸 여부 플래그를 받아들입니다. SaveDatabase 결과 단어 통계를 파일에 기록하고, 이후 실행 시 생성자를 통해 혹은 LoadDatabase. 테스트 그런 다음 0과 1 사이의 확률을 반환하여 새 메시지가 스팸일 가능성을 나타냅니다.

// Train the filter and store the word database
SharedPtr<SpamAnalyzer> teacher = MakeObject<SpamAnalyzer>();

for (String file : IO::Directory::GetFiles(u"hamFolder", u"*.eml"))
{
    // false marks the message as a regular one
    teacher->TrainFilter(MailMessage::Load(file), false);
}

for (String file : IO::Directory::GetFiles(u"spamFolder", u"*.eml"))
{
    // true marks the message as spam
    teacher->TrainFilter(MailMessage::Load(file), true);
}

teacher->SaveDatabase(u"SpamFilterDatabase.txt");

// Score new messages with the stored database
SharedPtr<SpamAnalyzer> analyzer = MakeObject<SpamAnalyzer>(u"SpamFilterDatabase.txt");

for (String file : IO::Directory::GetFiles(u"testFolder", u"*.eml"))
{
    SharedPtr<MailMessage> msg = MailMessage::Load(file);

    // a value between 0 and 1
    double probability = analyzer->Test(msg);

    Console::WriteLine(IO::Path::GetFileName(file) + u": " +
        (probability > 0.5 ? u"spam" : u"not spam") + u" (" + Convert::ToString(probability) + u")");
}

학습 코퍼스가 클수록 그리고 대표성이 높을수록 점수는 더 유용해집니다; 소수의 메시지만으로도 범위 중간값에 가까운 값을 산출합니다.

프렐러와 에필로그 읽기

멀티파트 메시지는 첫 번째 파트 이전과 마지막 파트 이후에 텍스트를 담을 수 있습니다. 메일 클라이언트는 이를 표시하지 않으며—전통적으로 프렐러는 "This is a multi-part message in MIME format." 라는 줄을 포함합니다—하지만 필드를 이용해 추가 정보를 은밀히 전달하기도 합니다. 프렐러 및 에필로그 읽기 및 쓰기 권한을 모두 부여합니다.

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

// text placed before the first MIME part and after the last one
Console::WriteLine(u"Preamble: " + eml->get_Preamble());
Console::WriteLine(u"Epilogue: " + eml->get_Epilogue());

// both properties can be written as well
eml->set_Preamble(u"This is a multi-part message in MIME format.");
eml->set_Epilogue(u"End of the message.");
eml->Save(u"WithPreamble.eml", SaveOptions::get_DefaultEml());

SharedPtr<MailMessage> reloaded = MailMessage::Load(u"WithPreamble.eml");
Console::WriteLine(u"Reloaded preamble: " + reloaded->get_Preamble());

MDN 및 수신 확인을 통한 이메일 추적

Message Disposition Notification 은 수신자가 메시지를 열었음을 발신자에게 알립니다. 발신자는 이를 통해 요청합니다 ReadReceiptTo, 문자열 하나 또는 전체를 주소로 받아들입니다 MailAddressCollection. 수신 측에서 CreateReadReceipt 알림 메시지를 구축한 뒤 SMTP 클라이언트로 다시 전송합니다. Outlook 항목의 경우 요청이 다음과 같이 표현됩니다 MapiMessage::ReadReceiptRequested.

// Sender side: ask for a read receipt
SharedPtr<MailMessage> outgoing = MakeObject<MailMessage>(u"from@domain.com", u"to@domain.com",
    u"test MDN", u"This is a test message with a read receipt requested");

// a single address can be assigned as a string
outgoing->set_ReadReceiptTo(u"from@domain.com");

// or several addresses can be collected
SharedPtr<MailAddressCollection> addresses = MakeObject<MailAddressCollection>();
addresses->Add(u"from@domain.com");
addresses->Add(u"another@domain.com");
outgoing->set_ReadReceiptTo(addresses);

outgoing->Save(u"MdnRequested.eml", SaveOptions::get_DefaultEml());

// Recipient side: build the notification for a received message
SharedPtr<MailMessage> received = MailMessage::Load(u"MdnRequested.eml");
if (received->get_ReadReceiptTo()->get_Count() > 0)
{
    SharedPtr<MailMessage> receipt = received->CreateReadReceipt(u"to@domain.com", nullptr);
    receipt->Save(u"ReadReceipt.eml", SaveOptions::get_DefaultEml());
    Console::WriteLine(u"Receipt subject: " + receipt->get_Subject());
}

// The same request in an Outlook message
SharedPtr<MapiMessage> mapiMessage = MapiMessage::FromMailMessage(outgoing, MapiConversionOptions::get_UnicodeFormat());
mapiMessage->set_ReadReceiptRequested(true);
mapiMessage->Save(u"MdnRequested.msg");

에 의해 생성된 알림 CreateReadReceipt 주제가 있습니다 Read: <original subject> 두 번째 인수로 전달된 본문 텍스트; nullptr 기본값을 남겨 둡니다.