Email Messages Advanced Management

This article collects the features that go beyond composing and saving a message: controlling how a message is rendered, filtering spam, reading the hidden parts of a MIME structure and tracking whether a message was read.

The samples below use these headers and namespaces:

#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 converts the HTML body into plain text. Its second overload accepts a HyperlinkRenderingCallback - a delegate that receives the complete markup of every link and returns the text that should replace it. This is the place to decide whether the address of a link is kept, how it is decorated, or whether the link disappears entirely.

// 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)));

The first callback turns <a href="https://www.aspose.com/">Aspose.Email</a> into Aspose.Email<https://www.aspose.com/>, the second one leaves Aspose.Email.

Choose the Headers Shown in MHTML

When a message is exported to MHTML, the library writes a block of header lines above the body. RenderingHeaders of MhtSaveOptions decides which lines appear and in which order; the names come from the MhtTemplateName class. An empty collection means the default block.

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);

Write Every Header into the Output

The block above is a summary for the reader. To carry the complete set of MIME headers into the MHTML file instead, switch SaveAllHeaders on.

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);

Render a Calendar Event

A meeting saved as MHTML shows its details when MhtFormatOptions contains both RenderCalendarEvent and 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);

Individual lines of that block are formatted through FormatTemplates, a dictionary keyed by the same MhtTemplateName constants; assigning an empty string to a key removes the line from the output.

Score Messages with the Bayesian Spam Analyzer

SpamAnalyzer implements a Bayesian filter. It is first trained on messages you have already classified: TrainFilter takes a message and a flag saying whether it is spam. SaveDatabase writes the resulting word statistics to a file, which a later run loads through the constructor or LoadDatabase. Test then returns the probability, between 0 and 1, that a new message is spam.

// 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")");
}

The larger and the more representative the training corpora are, the more useful the score becomes; a handful of messages produces values close to the middle of the range.

Read the Preamble and the Epilogue

A multipart message may carry text before its first part and after its last one. Mail clients never display it - the preamble traditionally holds the line “This is a multi-part message in MIME format.” - but the fields are sometimes used to smuggle extra information. Preamble and Epilogue give read and write access to both.

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());

Email Tracking with MDN and Read Receipts

A Message Disposition Notification tells the sender that a message has been opened. The sender asks for it through ReadReceiptTo, which accepts a single address as a string or a whole MailAddressCollection. On the receiving side CreateReadReceipt builds the notification message, which is then sent back with an SMTP client. For Outlook items the request is expressed by 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");

The notification produced by CreateReadReceipt has the subject Read: <original subject> and the body text passed as the second argument; nullptr leaves the default one.