Zaawansowane zarządzanie wiadomościami e‑mail
Ten artykuł zbiera funkcje wykraczające poza tworzenie i zapisywanie wiadomości: kontrolowanie renderowania wiadomości, filtrowanie spamu, czytanie ukrytych części struktury MIME i śledzenie, czy wiadomość została odczytana.
Przykłady poniżej używają tych nagłówków i przestrzeni nazw:
#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;
Renderowanie hiperłączy z własnymi stylami
GetHtmlBodyText konwertuje ciało HTML na zwykły tekst. Jego drugie przeciążenie przyjmuje HyperlinkRenderingCallback - delegata, który otrzymuje pełny znacznik każdego linku i zwraca tekst, który ma go zastąpić. To miejsce, aby zdecydować, czy adres linku zostaje zachowany, jak jest ozdobiony, czy link ma zniknąć całkowicie.
// 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)));
Pierwsze wywołanie zwrotne przetwarza <a href="https://www.aspose.com/">Aspose.Email</a> do Aspose.Email<https://www.aspose.com/>, drugi pozostawia Aspose.Email.
Wybierz nagłówki wyświetlane w MHTML
Gdy wiadomość jest eksportowana do MHTML, biblioteka zapisuje blok linii nagłówków nad treścią. RenderingHeaders z MhtSaveOptions decyduje, które linie pojawią się i w jakiej kolejności; nazwy pochodzą z MhtTemplateName klasę. Pusta kolekcja oznacza domyślny blok.
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);
Zapisz każdy nagłówek do wyjścia
Powyższy blok jest podsumowaniem dla czytelnika. Aby przenieść pełny zestaw nagłówków MIME do pliku MHTML, przełącz SaveAllHeaders na.
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);
Renderowanie wydarzenia kalendarza
Spotkanie zapisane jako MHTML pokazuje szczegóły, gdy MhtFormatOptions zawiera oba RenderCalendarEvent i 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);
Pojedyncze linie tego bloku są formatowane przez FormatTemplates, słownik kluczowany tym samym MhtTemplateName stałych; przypisanie pustego ciągu kluczowi usuwa tę linię z wyjścia.
Punktuj wiadomości przy użyciu analizatora bayesowskiego spamu
SpamAnalyzer implementuje filtr bayesowski. Najpierw jest trenowany na wiadomościach, które już sklasyfikowałeś: TrainFilter przyjmuje wiadomość i flagę określającą, czy jest spamem. SaveDatabase zapisuje uzyskane statystyki słów do pliku, który późniejsze uruchomienie wczytuje przez konstruktor lub LoadDatabase. Test zwraca następnie prawdopodobieństwo, od 0 do 1, że nowa wiadomość jest spamem.
// 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")");
}
Im większe i bardziej reprezentatywne są korpusy treningowe, tym użyteczniejszy staje się wynik; kilka wiadomości daje wartości bliskie środkowi zakresu.
Przeczytaj przedmowę i epilog
Wiadomość wieloczęściowa może zawierać tekst przed pierwszą częścią i po ostatniej. Klienci poczty nigdy go nie wyświetlają – przedmowa tradycyjnie zawiera wiersz „This is a multi-part message in MIME format.” – ale pola są czasami używane do przemycania dodatkowych informacji. Przedmowa i Epilog przyznaje dostęp odczytu i zapisu do obu.
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());
Śledzenie e‑maili przy użyciu MDN i potwierdzeń odczytu
Powiadomienie o dyspozycji wiadomości informuje nadawcę, że wiadomość została otwarta. Nadawca prosi o to przez ReadReceiptTo, które przyjmuje pojedynczy adres jako ciąg znaków lub całą MailAddressCollection. Po stronie odbiorczej CreateReadReceipt tworzy wiadomość powiadomienia, która jest następnie wysyłana z klientem SMTP. W przypadku elementów Outlook żądanie jest wyrażone przez 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");
Powiadomienie wygenerowane przez CreateReadReceipt ma temat Read: <original subject> oraz tekst główny przekazany jako drugi argument; nullptr zostawia domyślną.