Email Messages Advanced Management
Track Document Conversion Progress
Aspose.Email provides the facility to track the document conversion progress. For this, the API provides SaveOptions.CustomProgressHandler. which represents the method that handles the progress events. The progress event types are represented by the ProgressEventType enumeration. The ProgressEventType enumeration has the following members.
- MimeStructureCreated: This event informs that the mime structure is created.
- MimePartSaved: This event informs that saving of one mime part is finished.
- SavedToStream: This event informs that all mime parts are saved to stream.
The following sample code demonstrates the use of SaveOptions.CustomProgressHandler and ProgressEventType enumeration track the document conversion progress.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// The path to the File directory. | |
string dataDir = RunExamples.GetDataDir_Email(); | |
var fileName = dataDir + "test.eml"; | |
MailMessage msg = MailMessage.Load(fileName); | |
MemoryStream ms = new MemoryStream(); | |
EmlSaveOptions opt = new EmlSaveOptions(MailMessageSaveType.EmlFormat); | |
opt.CustomProgressHandler = new ConversionProgressEventHandler(ShowEmlConversionProgress); | |
msg.Save(ms, opt); |
The following is the code for the custom class used in the code sample given above.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
private static void ShowEmlConversionProgress(ProgressEventHandlerInfo info) | |
{ | |
int total; | |
int saved; | |
switch (info.EventType) | |
{ | |
case ProgressEventType.MimeStructureCreated: | |
total = info.TotalMimePartCount; | |
saved = info.SavedMimePartCount; | |
Console.WriteLine("MimeStructureCreated - TotalMimePartCount: " + total); | |
Console.WriteLine("MimeStructureCreated - SavedMimePartCount: " + saved); | |
break; | |
case ProgressEventType.MimePartSaved: | |
total = info.TotalMimePartCount; | |
saved = info.SavedMimePartCount; | |
Console.WriteLine("MimePartSaved - TotalMimePartCount: " + total); | |
Console.WriteLine("MimePartSaved - SavedMimePartCount: " + saved); | |
break; | |
case ProgressEventType.SavedToStream: | |
total = info.TotalMimePartCount; | |
saved = info.SavedMimePartCount; | |
Console.WriteLine("SavedToStream - TotalMimePartCount: " + total); | |
Console.WriteLine("SavedToStream - SavedMimePartCount: " + saved); | |
break; | |
} | |
} |
Render Hyperlinks with Custom Styles
There may be times when you need to output hyperlinks with some specific style based on the requirements of your application. For that, Aspose.Email provides HyperlinkRenderingCallback. You can pass the HyperlinkRenderingCallback as a parameter of MailMessage.GetHtmlBodyText.
The following code snippet shows you how to use HyperlinkRenderingCallback to output hyperlinks using your own custom style.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
public static void Run() | |
{ | |
string dataDir = RunExamples.GetDataDir_Email(); | |
var fileName = dataDir + "LinksSample.eml"; | |
MailMessage msg = MailMessage.Load(fileName); | |
Console.WriteLine(msg.GetHtmlBodyText(RenderHyperlinkWithHref)); | |
Console.WriteLine(msg.GetHtmlBodyText(RenderHyperlinkWithoutHref)); | |
} | |
private static string RenderHyperlinkWithHref(string source) | |
{ | |
int start = source.IndexOf("href=\"") + "href=\"".Length; | |
int end = source.IndexOf("\"", start + "href=\"".Length); | |
string href = source.Substring(start, end - start); | |
start = source.IndexOf(">") + 1; | |
end = source.IndexOf("<", start); | |
string text = source.Substring(start, end - start); | |
string link = string.Format("{0}<{1}>", text, href); | |
return link; | |
} | |
private static string RenderHyperlinkWithoutHref(string source) | |
{ | |
int start = source.IndexOf(">") + 1; | |
int end = source.IndexOf("<", start); | |
string text = source.Substring(start, end - start); | |
return text; | |
} |
Display Information in Custom Order in MHTML Files
Aspose.Email provides MhtSaveOptions.RenderingHeaders property which returns the list of headers for rendering. You can add the headers by using the MhtTemplateName class. The order in which the headers are added decides the order in which the information is displayed.
The following image compares the three outputs generated by the sample code.
The following code snippet demonstrates the use of MhtSaveOptions.RenderingHeaders property to set the order in which the information is displayed in the output MHTML files.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// The path to the File directory. | |
string dataDir = RunExamples.GetDataDir_Email(); | |
MailMessage eml = MailMessage.Load(dataDir + "Attachments.eml"); | |
MhtSaveOptions opt = SaveOptions.DefaultMhtml; | |
eml.Save(dataDir + "CustomOrderOfInformationInMHTML_1.mhtml", opt); | |
opt.RenderingHeaders.Add(MhtTemplateName.From); | |
opt.RenderingHeaders.Add(MhtTemplateName.Subject); | |
opt.RenderingHeaders.Add(MhtTemplateName.To); | |
opt.RenderingHeaders.Add(MhtTemplateName.Sent); | |
eml.Save(dataDir + "CustomOrderOfInformationInMHTML_2.mhtml", opt); | |
opt.RenderingHeaders.Clear(); | |
opt.RenderingHeaders.Add(MhtTemplateName.Attachments); | |
opt.RenderingHeaders.Add(MhtTemplateName.Cc); | |
opt.RenderingHeaders.Add(MhtTemplateName.Subject); | |
eml.Save(dataDir + "CustomOrderOfInformationInMHTML_3.mhtml", opt); |
Display Optional Attendees in MHT Files
When working with the MHT format, you can display or hide information about optional attendees in the header of calendar events. To configure MhtSaveOptions for MHT files handling, you need to understand how the MhtFormatOptions.RenderCalendarEvent and MhtFormatOptions.WriteHeader parameters work in customizing the output according to your needs, particularly when managing the display of optional attendees.
-
MhtFormatOptions.RenderCalendarEvent: This parameter controls whether details of calendar events are rendered in the MHT file. By setting this option, you ensure that comprehensive event information, including attendee details, is included in the output. This is essential for providing complete documentation of calendar events.
-
MhtFormatOptions.WriteHeader: This parameter determines if headers containing metadata such as subject, date, and participant information (including optional attendees, when configured) are written into the MHT file. Enabling this option ensures that contextually relevant information accompanies your message, enhancing understandability.
The code sample below demonstrates how to use display optional attendees feature when saving an msg in mhtml format:
MhtSaveOptions options = new MhtSaveOptions()
{
MhtFormatOptions = MhtFormatOptions.RenderCalendarEvent | MhtFormatOptions.WriteHeader
};
MailMessage eml = MailMessage.Load(fileName);
eml.Save(fileName + ".mhtml", options);
If you need to exclude information about optional attendees from the MHT file, simply clear the format template for OptionalAttendees before saving:
//if you need to skip OptionalAttendees in mhtml file you can clear format template for OptionalAttendees
options.FormatTemplates[MhtTemplateName.OptionalAttendees] = "";
msg.Save(fileName + "2.mhtml", options);
Save All Headers in MHTML
The MhtSaveOptions.SaveAllHeaders property of the MhtSaveOptions class defines whether there is a need to save all headers in output mhtml or not. The following code snippet shows you how to save all headers of an mhtml file:
var eml = MailMessage.Load("message.eml");
var sopt = SaveOptions.DefaultMhtml;
sopt.SaveAllHeaders = true;
eml.Save("message.mhtml", sopt);
Processing Bounced Messages
It is very common that a message sent to a recipient may bounce for any reason such as an invalid recipient address. Aspose.Email API has the capability to process such a message for checking if it is a bounced email or a regular email message. The CheckBounced method of the MailMessage class returns a valid result if the email message is a bounced email. This article shows the usage of the BounceResult class that provides the capability of checking if a message is a bounced email. It further gives detailed information about the recipients, action taken and the reason for the notification. The following code snippet shows you how to process bounced messages.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string fileName = RunExamples.GetDataDir_Email() + "failed1.msg"; | |
MailMessage mail = MailMessage.Load(fileName); | |
BounceResult result = mail.CheckBounced(); | |
Console.WriteLine(fileName); | |
Console.WriteLine("IsBounced : " + result.IsBounced); | |
Console.WriteLine("Action : " + result.Action); | |
Console.WriteLine("Recipient : " + result.Recipient); | |
Console.WriteLine(); | |
Console.WriteLine("Reason : " + result.Reason); | |
Console.WriteLine("Status : " + result.Status); | |
Console.WriteLine("OriginalMessage ToAddress 1: " + result.OriginalMessage.To[0].Address); | |
Console.WriteLine(); |
Bayesian Spam Analyzer
Aspose.Email provides email filtering using a Bayesian spam analyzer. It provides the SpamAnalyzer class for this purpose. This article shows how to train the filter to distinguish between spam and regular emails based on the words database.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
string hamFolder = RunExamples.GetDataDir_Email() + "/hamFolder"; | |
string spamFolder = RunExamples.GetDataDir_Email() + "/Spam"; | |
string testFolder = RunExamples.GetDataDir_Email(); | |
string dataBaseFile = RunExamples.GetDataDir_Email() + "SpamFilterDatabase.txt"; | |
TeachAndCreateDatabase(hamFolder, spamFolder, dataBaseFile); | |
string[] testFiles = Directory.GetFiles(testFolder, "*.eml"); | |
SpamAnalyzer analyzer = new SpamAnalyzer(dataBaseFile); | |
foreach (string file in testFiles) | |
{ | |
MailMessage msg = MailMessage.Load(file); | |
Console.WriteLine(msg.Subject); | |
double probability = analyzer.Test(msg); | |
PrintResult(probability); | |
} |
Obtain Preamble and Epilogue from EML Messages
An email message may contain some hidden information as a plain text before the message body (i.e. preamble) or after the body (i.e. epilogue). It is typically some additional information or context to the recipient before or after they read the main content of the email. You can obtain this information using MailMessage.Preamble or/and MailMessage.Epilogue properties respectively.
The following code snippet shows how to obtain the preamble and epilogue texts:
// Gets or sets a preamble text.
public string Preamble
// Gets or sets an epilogue text.
public string Epilogue
Email Tracking using MDN and Read Receipts
Aspose.Email API provides support of email tracking using Message Disposition Notification (MDN). This is achieved by requesting the read receipts and creating the required information. The MailMessage.ReadReceiptTo property gets or sets the set read receipt address. The CreateReadReceipt and ReadReceiptRequested methods are used for creating and retrieving the information whether read receipts are requested. The following code snippet shows you how to email track using Aspose.Email API.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Send message with the requested read receipt | |
MailMessage mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
// request the read receipt | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
SendMessage(mailMessage, SendMethod.SMTP); | |
// Add multiple ReadReceiptTo addresses. Send message with the requested read receipt. | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
var addressCollection = new Aspose.Email.Mail.MailAddressCollection(); | |
addressCollection.Add("fromAddress"); | |
addressCollection.Add(anotherAddress); | |
mailMessage.ReadReceiptTo = addressCollection; | |
SendMessage(mailMessage, SendMethod.SMTP); | |
// Send message by Exchange | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
SendMessage(mailMessage, SendMethod.Exchange); | |
// Check the request, create and send read receipt. | |
MailMessage emlMDN = FetchMessage(); | |
if (emlMDN.ReadReceiptTo.Count > 0) | |
{ | |
SendMessage(emlMDN.CreateReadReceipt("toAddress", null), SendMethod.SMTP); | |
} | |
// Create the MapiMessage with requested read receipt | |
MapiMessage mapiMessage = new MapiMessage("fromAddress", "toAddress", "test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode); | |
mapiMessage.ReadReceiptRequested = true; | |
// Create the MailMessage with requested read receipt and convert it to MapiMessage | |
mailMessage = new MailMessage("fromAddress", "toAddress", "test MDN","This is a test message with read receipt requested"); | |
mailMessage.ReadReceiptTo = "fromAddress"; | |
mapiMessage = MapiMessage.FromMailMessage(mailMessage, MapiConversionOptions.UnicodeFormat); | |
mapiMessage = new MapiMessage("dmitry.samodurov@aspose.com", "dmitry.samodurov@aspose.com", "test MDN", "This is a read requested mapiMessage", OutlookMessageFormat.Unicode); | |
mapiMessage.ReadReceiptRequested = true; | |
var getData = MailMessageInterpretorFactory.Instance.GetIntepretor(mapiMessage.MessageClass); | |
var getMessage = mi.Interpret(mapiMessage); |