Managing Message Files with Aspose.Email.Outlook

Getting a MAPI item type

The MapiItemType enum represents a MAPI item type that can be explicitly converted into an object of the corresponding class derived from the IMapiMessageIteminterface. This way users can avoid checking the MessageClass property value before message conversion.

The following code sample shows how to define a type for the item to be converted:

foreach (var messageInfo in folder.EnumerateMessages())
{
    var msg = pst.ExtractMessage(messageInfo);

    switch (msg.SupportedType)
    {
        // Non-supported type. MapiMessage cannot be converted to an appropriate item type.
        // Just use in MSG format.
        case MapiItemType.None:
            break;
        // An email message. Conversion isn't required.
        case MapiItemType.Message:
            break;
        // A contact item. Can be converted to MapiContact.
        case MapiItemType.Contact:
            var contact = (MapiContact)msg.ToMapiMessageItem();
            break;
        // A calendar item. Can be converted to MapiCalendar.
        case MapiItemType.Calendar:
            var calendar = (MapiCalendar)msg.ToMapiMessageItem();
            break;
        // A distribution list. Can be converted to MapiDistributionList.
        case MapiItemType.DistList:
            var dl = (MapiDistributionList)msg.ToMapiMessageItem();
            break;
        // A Journal entry. Can be converted to MapiJournal.
        case MapiItemType.Journal:
            var journal = (MapiJournal)msg.ToMapiMessageItem();
            break;
        // A StickyNote. Can be converted to MapiNote.
        case MapiItemType.Note:
            var note = (MapiNote)msg.ToMapiMessageItem();
            break;
        // A Task item. Can be converted to MapiTask.
        case MapiItemType.Task:
            var task = (MapiTask)msg.ToMapiMessageItem();
            break;
    }
}

Saving Email as HTML

Aspose.Email makes it possible to save email resources with relative paths when exporting messages to HTML format. This feature provides more flexibility in how resources are linked in the output HTML file, making it easier to share and display saved emails on different systems. In order to save resources with relative paths, use HtmlSaveOptions.UseRelativePathToResources property. The default property value is false (resources are saved with absolute paths). When set to true, resources are saved with relative paths.

HTML files with relative paths are more portable and can be viewed correctly regardless of the hosting environment’s file structure. You can choose between absolute and relative paths depending on the requirements. You can define custom paths for resources using the ResourceHtmlRendering event.

The following code sample demonstrates how to save an email with default relative path to resources:

var msg = MapiMessage.Load(sourceFileName);

var htmlSaveOptions = new HtmlSaveOptions
{
    ResourceRenderingMode = ResourceRenderingMode.SaveToFile,
    UseRelativePathToResources = true
};

msg.Save(Path.Combine("target_files"), htmlSaveOptions);

In this case, resources will be saved in the [html file name]_files folder, in the same path as the .html file and the HTML will reference the resources via relative paths.

The code sample below demonstrates how to save with absolute path to resources:

var msg = MapiMessage.Load(sourceFileName);

var htmlSaveOptions = new HtmlSaveOptions
{
    ResourceRenderingMode = ResourceRenderingMode.SaveToFile,
    UseRelativePathToResources = false
};

msg.Save(Path.Combine("target_files"), htmlSaveOptions);

As in the first case, resources will be saved in the [html file name]_files folder by default, but the HTML will reference resources using absolute paths.

By using the ResourceHtmlRendering event, you can set custom relative or absolute paths for resources. When customizing paths with the ResourceHtmlRendering event handler, and since UseRelativePathToResources is set to true, you should assign a relative path to the PathToResourceFile property to ensure correct referencing.

The following code sample demonstrates how to custom relative path using ResourceHtmlRendering Event

var msg = MapiMessage.Load(sourceFileName);

var htmlSaveOptions = new HtmlSaveOptions
{
    ResourceRenderingMode = ResourceRenderingMode.SaveToFile,
    UseRelativePathToResources = true
};

htmlSaveOptions.ResourceHtmlRendering += (o, args) =>
{
    if (o is AttachmentBase attachment)
    {
	    // Since UseRelativePathToResources = true, you should assign a relative path to the PathToResourceFile property.
        args.PathToResourceFile = $@"images\{attachment.ContentType.Name}";
    }
};

msg.Save(Path.Combine(targetPath, "A Day in the Park.html"), htmlSaveOptions);

Converting MSG to MIME message

Aspose.Email API provides the capability of converting MSG files to MIME messages using the ToMailMessage method.

Setting Timeout to Message Conversion and Loading Process

The following features will enable you to set the timeout in milliseconds for conversion and loading process:

The code sample below will show you how to set timeout while converting a message:

var options = new MailConversionOptions();
// Set the timeout to 5 seconds
options.Timeout = 5000;

options.TimeoutReached += (object sender, EventArgs args) =>
{
    string subj = (sender as MailMessage).Subject;
	 // Set a flag indicating the timeout was reached
    isTimedOut = true;
};

var mailMessage = mapiMessage.ToMailMessage(options);

Reading and Writing Outlook Template File (.OFT)

Outlook templates are very useful when you want to send a similar email message again and again. Instead of preparing the message from scratch each time, first, prepare the message in Outlook and save it as an Outlook Template (OFT). After that, whenever you need to send the message, you can create it from the template, saving time writing the same text in the body or the subject line, setting formatting and so on. Aspose.Email’s MailMessage class can be used to load and read an Outlook template (OFT) file. Once the Outlook template is loaded in an instance of the MailMessage class, you can update the sender, recipient, body, subject and other properties. After updating the properties:

  • Send the email using the SmtpClient class or
  • Save the message as MSG and do further updates/validation using Microsoft Outlook.

In the code samples below, we:

  1. Load the template using the MailMessage class.
  2. Update some of the properties.
  3. Save the message in MSG format.

The following code snippet shows you how to load the OFT file, updating the message and saving it in MSG format.

Saving Outlook MSG file as Template

The following code snippet shows you how to save the outlook MSG file as a template.

Determine if a MapiMessage is OFT or MSG

When loading a MapiMessage object from a file, you may need to determine if the loaded message is a template file or a regular email file. By using the IsTemplate property of the MapiMessage class, you can accurately detect whether an email is a template or not. This functionality can be valuable when handling and processing various types of email files within applications and systems.

The code example below demonstrates how to determine if a MapiMessage is OFT or MSG:

var msg = MapiMessage.Load("message.msg");
var isOft = msg.IsTemplate; // returns false

var msg = MapiMessage.Load("message.oft");
var isOft = msg.IsTemplate; // returns true

Saving MapiMessage or MailMessage in OFT format

The SaveOptions class allows you to specify additional options when saving a MailMessage or MapiMessage into a particular format.

The following code sample demonstrates how to save a message to OFT format:

// Save the MailMessage to OFT format
using (var eml = MailMessage.Load("message.eml"))
{
    eml.Save("message.oft", SaveOptions.DefaultOft);
	
	// or alternative way #2
	var saveOptions = new MsgSaveOptions(MailMessageSaveType.OutlookTemplateFormat);
    eml.Save("message.oft", saveOptions);
	
	// or alternative  way #3
	saveOptions = SaveOptions.CreateSaveOptions(MailMessageSaveType.OutlookTemplateFormat);
    eml.Save("message.oft", saveOptions);

}

// Save the MapiMessage to OFT format
using (var msg = MapiMessage.Load("message.msg"))
{
    msg.Save("message.oft", SaveOptions.DefaultOft);
	
	// or alternative way #2
	var saveOptions = new MsgSaveOptions(MailMessageSaveType.OutlookTemplateFormat);
    msg.Save("message.oft", saveOptions);
	
	// or alternative  way #3
	saveOptions = SaveOptions.CreateSaveOptions(MailMessageSaveType.OutlookTemplateFormat);
    msg.Save("message.oft", saveOptions);
}

Managing Digitally Signed Messages

Aspose.Email implements the complete S/MIME email object algorithm. This gives the API complete power to preserve digital signatures while converting messages between formats.

Preserving Signature when Converting from EML to MSG

Aspose.Email preserves the digital signature when converting from EML to MSG. The following code snippet shows you how to convert from EML to MSG.

Converting S/MIME Messages from MSG to EML

Aspose.Email preserves the digital signature when converting from MSG to EML as shown in the following code snippet.

Checking the Signature of Secure Emails

The following features are available to check the signature of MapiMessage objects.

The code sample below shows how to implement the features in your project:

var msg = MapiMessage.Load(fileName, new EmlLoadOptions());
var result = new SecureEmailManager().CheckSignature(msg);

var certFileName = "cert.pfx";
var cert = new X509Certificate2(certFileName, "pass");
var eml = MapiMessage.Load(fileName);
var store = new X509Store();
store.Open(OpenFlags.ReadWrite);
store.Add(cert);
store.Close();

var result = new SecureEmailManager().CheckSignature(eml, cert, store);

Removing a Signature from a MapiMessage

For better compatibility, the MapiMessage.RemoveSignature method and MapiMessage.IsSigned property are used to remove a digital signature from a message.

The follwoing code snippet shows how to implement these features into your project:

var msg = MapiMessage.Load(fileName);

if (msg.IsSigned)
{
    var unsignedMsg = msg.RemoveSignature();
}

Decrypt a MapiMessage with Certificate

If you have encrypted MAPI messages and need to decrypt them using the private key stored in a certificate, the following features of Aspose.Email can be useful:

The following code snippet shows how to work with encrypted MAPI messages:

var privateCert = new X509Certificate2(privateCertFile, "password");
var msg = MapiMessage.Load("encrypted.msg");

if (msg.IsEncrypted);
{
    var decryptedMsg = msg.Decrypt(privateCert);
}

Setting Color Category for Outlook MSG Files

A color category marks an email message for some kind of importance or category. Microsoft Outlook lets users assign color categories to differentiate emails. To handle the color category, use the FollowUpManager. It contains functions such as AddCategory, RemoveCategory, ClearCategories and GetCategories.

  • AddCategory takes MapiMessage and the color category string, for example, “Purple Category” or “Red Category” as arguments.
  • RemoveCategory takes MapiMessage and the color category string to be removed from the message.
  • ClearCategories is used to remove all the color categories from the message.
  • GetCategories is used to retrieve all the color categories from a particular message.

The following example performs the tasks as given below:

  1. Add a color category.
  2. Add another color category.
  3. Retrieve the list of all categories.
  4. Remove all categories.

Accessing Follow Up Information from MSG file

Aspose.Email API provides the capability to access the follow-up information from a sent or received message. It can retrieve the Read, Delivery Read Receipt and vote results information from a message file.

Retrieving Read and Delivery Receipt Information

The following code snippet shows you how to retrieve read and delivery receipt information.

Creating Forward and Reply Messages

Aspose.Email API provides the capability of creating and formatting the forward and reply messages. The ReplyMessageBuilder and ForwardMessageBuilder classes of the API are used to create the Reply and Forward messages respectively. A Reply or Forward message can be specified to be created using any of the modes of OriginalMessageAdditionMode enum. This enum has the following values:

  • OriginalMessageAdditionMode.None - The original message is not included in the response message.
  • OriginalMessageAdditionMode.Attachment - The original message is included as an attachment in the response message
  • OriginalMessageAdditionMode.Textpart - The original message is included as a text in the body of response message

Creating a Reply Message

The following code snippet shows you how to create a reply message.

Creating a Forward Message

The following code snippet shows you how to create a forward message.