Load and Save Email Message

Load Email Message

Load from EML

This section describes how to load an EML file into a MailMessage object using the EmlLoadOptions class. The EmlLoadOptions class provides various options to customize how the EML file is loaded, such as preserving embedded message formats or controlling TNEF attachment loading behavior.

  1. Initialize an instance of EmlLoadOptions.
  2. Configure the load options as needed.
  3. Use the MailMessage.Load() method to load the EML file with the specified options.
using Aspose.Email;

// Initialize EmlLoadOptions
var loadOptions = new EmlLoadOptions
{
    // Configure load options
    PreferredTextEncoding = Encoding.UTF8, // Sets preferred encoding for the message
    PreserveEmbeddedMessageFormat = true, // Preserve format of embedded messages
    PreserveTnefAttachments = true, // Control TNEF attachment loading
    RemoveSignature = false // Do not remove the signature
};

// Load the EML file
var eml = MailMessage.Load("file.eml", loadOptions);

Properties of EmlLoadOptions

Preserve Embedded Message Format

Load Message With Signature/Without Signature

Signature preservation is supported by default when loading EML files. To remove the signature, you can set the LoadOptions.RemoveSignature property to true.

The code sample below shows how to remove a signature when loading a message:

var msg = MapiMessage.Load(fileName, new EmlLoadOptions() { RemoveSignature = true});

Load from EMLX

The following section covers loading an EMLX file with the EmlxLoadOptions class. This class provides options similar to EmlLoadOptions, offering control over encoding, signature removal, and more.

  1. Instantiate the EmlxLoadOptions.
  2. Configure properties as necessary.
  3. Use the MailMessage.Load() method to load the EMLX file.
using Aspose.Email;

// Instantiate EmlxLoadOptions
var loadOptions = new EmlxLoadOptions
{
    // Configure load options
    PreferredTextEncoding = Encoding.UTF8, // Set encoding preference
    PreserveEmbeddedMessageFormat = true, // Preserve embedded message formats
    RemoveSignature = true // Remove signatures during loading
};

// Load the EMLX file
var emlx = MailMessage.Load("file.emlx", loadOptions);

Properties of EmlxLoadOptions

Load from HTML

Learn how to load an HTML file into a MailMessage using the HtmlLoadOptions class. This class is specifically designed to handle HTML content with options to manage resources and add plain text views.

  1. Initialize an instance of HtmlLoadOptions.
  2. Configure the necessary properties.
  3. Use the MailMessage.Load() method to load the HTML file with the specified options.
using Aspose.Email;

// Initialize HtmlLoadOptions
var loadOptions = new HtmlLoadOptions
{
    // Configure load options
    PathToResources = "resources/", // Path to directory containing resource files
    PreferredTextEncoding = Encoding.UTF8, // Set encoding preference
    ShouldAddPlainTextView = true // Add plain text view of the body
};

// Load the HTML file
var html = MailMessage.Load("file.html", loadOptions);

Properties of HtmlLoadOptions

Load from MHTML

This section explains how to load an MHTML file using the MhtmlLoadOptions class. The MhtmlLoadOptions class offers options to manage encoding, preserve embedded message formats, and handle TNEF attachments.

  1. Create an instance of MhtmlLoadOptions.
  2. Configure the desired properties.
  3. Load the MHTML file using the MailMessage.Load() method.
using Aspose.Email;

// Create MhtmlLoadOptions
var loadOptions = new MhtmlLoadOptions
{
    // Set load options
    PreferredTextEncoding = Encoding.UTF8, // Set encoding preference
    PreserveEmbeddedMessageFormat = true, // Preserve format of embedded messages
    PreserveTnefAttachments = true, // Handle TNEF attachments
    RemoveSignature = false // Keep the signature
};

// Load the MHTML file
var mhtml = MailMessage.Load("file.mht", loadOptions);

Properties of MhtmlLoadOptions

Load from MSG

This section explains how to load an MSG file into a MailMessage object using the MsgLoadOptions class. The MsgLoadOptions class offers various properties to handle how MSG files are loaded, including options to preserve RTF content or manage TNEF attachments.

  1. Create an instance of MsgLoadOptions.
  2. Set the desired properties to customize loading.
  3. Load the MSG file using the MailMessage.Load() method.
using Aspose.Email;

// Create MsgLoadOptions
var loadOptions = new MsgLoadOptions
{
    // Set load options
    KeepOriginalEmailAddresses = true, // Preserve original email addresses
    PreferredTextEncoding = Encoding.UTF8, // Set preferred encoding
    PreserveRtfContent = true, // Keep RTF content in the message
    PreserveTnefAttachments = true, // Handle TNEF attachments
    RemoveSignature = false, // Keep the signature
    Timeout = 5000 // Set timeout to 5 seconds
};

// Load the MSG file
var msg = MailMessage.Load("file.msg", loadOptions);

Properties of MsgLoadOptions

Load from TNEF

Learn how to load a TNEF eml file with the TnefLoadOptions class. This class provides options to manage encoding and remove signatures during the loading process.

  1. Instantiate the TnefLoadOptions.
  2. Configure the properties as needed.
  3. Use the MailMessage.Load() method to load the TNEF file.
using Aspose.Email;

// Instantiate TnefLoadOptions
var loadOptions = new TnefLoadOptions
{
    // Configure load options
    PreferredTextEncoding = Encoding.UTF8, // Set encoding preference
    PreserveEmbeddedMessageFormat = true, // Preserve embedded message formats
    RemoveSignature = true // Remove signatures during loading
};

// Load the TNEF file
var tnef = MailMessage.Load("file.eml", loadOptions);

Properties of TnefLoadOptions

  • MessageFormat: Represents the mail message format, such as EML, MSG, or MHTML. Default is EML.
  • PreferredTextEncoding: Sets preferred encoding for message subject and body. Default is null.
  • PreserveEmbeddedMessageFormat: Indicates whether to preserve the format of embedded messages. Default is false.
  • RemoveSignature: Specifies whether to remove the signature during loading. Default is false.

Detecting File Formats

Aspose.Email API provides the capability to detect the file format of the provided message file. The DetectFileFormat method of FileFormatUtil class can be used to achieve this. The following classes and methods can be used to detect the loaded file format.

The following code snippet shows you how to detect file formats.

Save and Convert Messages

Aspose.Email makes it easy to convert any message type to another format. To demonstrate this feature, the code in this article loads three types of messages from disk and saves them back in other formats. The base class SaveOptions and the classes EmlSaveOptions, MsgSaveOptions, MhtSaveOptions, HtmlSaveOptions for additional settings when saving MailMessage can be used for saving messages to other formats. The article shows how to use these classes to save a sample email as:

  • EML format.
  • Outlook MSG.
  • MHTML format.
  • HTML format.

Save to EML

The following code snippet shows you how to load an EML message and saves it to the disc in the same format.

Preserve the Original Boundaries

The following code snippet shows you how to load EML and save as EML preserving the original boundaries.

Preserve TNEF Attachments

The following code snippet shows you how to save as EML preserving TNEF attachments.

Save EML to MSG

The following code snippet shows you how to load an EML message and convert it to MSG using the appropriate option from SaveOptions.

Preserve Dates

The MsgSaveOptions class allows you to save the source message as an Outlook Message file (MSG) preserving dates. The following code snippet shows you how to save as MSG with Preserved Dates.

Save EML to MHTML

Different options of MHTML can be used to obtain the desired results. The following code snippet shows you how to load an EML message into MailMessage and convert it to MHTML with a message date in the UTC system.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET

// Set options for MHTML output
MhtSaveOptions saveOptions = SaveOptions.DefaultMhtml;
saveOptions.PreserveOriginalDate = false; // save a message date as UTC date

// Initialize and load an existing EML file
using (MailMessage mailMessage = MailMessage.Load(folderPath + "Message.eml"))
{
    mailMessage.Save(folderPath + "Message_out.mhtml", saveOptions);
}

Conversion Options

The MhtSaveOptions class provides additional options for saving email messages to MHTML format. The enumerator MhtFormatOptions makes it possible to write additional email information to the output MHTML. The following additional fields can be written:

  • WriteHeader – write the email header to the output file.
  • WriteOutlineAttachments – write outline attachments to the output file.
  • WriteCompleteEmailAddress – write the complete email address to the output file.
  • NoEncodeCharacters – no transfer encoding of characters should be used.
  • HideExtraPrintHeader – hide extra print header from the top of the output file.
  • WriteCompleteToEmailAddress – write the complete recipient email address to the output file.
  • WriteCompleteFromEmailAddress – write the complete sender email address to the output file.
  • WriteCompleteCcEmailAddress – write the complete email addresses of any carbon-copied recipients to the output file.
  • WriteCompleteBccEmailAddress – write the complete email address of any blind carbon-copied recipients to the output file.
  • RenderCalendarEvent – write text from the calendar event to the output file.
  • SkipByteOrderMarkInBody – write Byte Order Mark(BOM) bytes to the output file.
  • RenderVCardInfo – write text from VCard AlternativeView to the output file.
  • DisplayAsOutlook – display From header.
  • RenderTaskFields – writes specific Task fields to the output file.
  • None – No setting specified.

The following code snippet shows you how to convert EML files to MHTML with optional settings.

Render Calendar Events

The MhtFormatOptions.RenderCalendarEvent renders the Calendar events to the output MTHML. The following code snippet shows you how to render calendar events while converting to MHTML.

Exporting Email to MHT without Inline Images

Exporting Email to MHT with customized TimeZone

MailMessage class provides the TimeZoneOffset property to set customized Timezone while exporting to MHT. The following code snippet shows you how to export email to MHT with customized TimeZone.

Font Adjustment

Save EML to HTML

The HtmlSaveOptions class allows you to export the message body to HTML. The following code snippet shows you how to save a message as HTML.

Save without Embedded Resources

Save EML to OFT

The following code snippet shows you how to save a message as an outlook template (.oft) file.

Convert EML to MSG (MailMessage to MapiMessage)

To convert a MailMessage object loaded from an EML file to a MapiMessage object, use the MapiConversionOptions class. This conversion is often necessary because these two objects serve different purposes and cater to distinct needs in email processing. MapiMessage is specifically designed for compatibility with Microsoft Outlook and Exchange Server, as it adheres to the Messaging Application Programming Interface (MAPI) format. This ensures that emails converted to MSG files are fully compatible with Microsoft products, allowing them to be opened, modified, and managed directly within Outlook.

This conversion is also necessary when emails need to be archived, indexed, or processed by storages that require the MAPI format, PST/OST, OLM storages, for example. The MapiConversionOptions class allows you to specify additional options, such as preserving the original message format, keeping original dates, and compressing the RTF body during conversion. The following code sample shows how to load an email from a file in .eml format and convert it into an Outlook .msg format allowing for customization but ensuring that certain characteristics of the original email are preserved during the conversion.

  1. Create an instance of MapiConversionOptions and configure its properties.
  2. Convert the MailMessage object to a MapiMessage object using the configured conversion options.
MailMessage eml = MailMessage.Load("email.eml", new EmlLoadOptions());

// Create an instance of MapiConversionOptions
var conversionOptions = new MapiConversionOptions
{
    // Configure MapiConversionOptions
    Format = OutlookMessageFormat.Unicode, // Use Unicode format for MSG
    PreserveEmbeddedMessageFormat = true, // Preserve the format of embedded messages
    PreserveOriginalAddresses = true, // Keep original email addresses
    PreserveOriginalDates = true, // Preserve original dates
    PreserveEmptyDates = false, // Generate new dates if original are empty
    RemoveSignature = false, // Do not remove the signature
    UseBodyCompression = true, // Enable RTF body compression
    ForcedRtfBodyForAppointment = false // Disable forced RTF body for appointments
};

// Convert MailMessage to MapiMessage
MapiMessage msg = MapiMessage.FromMailMessage(eml, conversionOptions);

Available Properties of MapiConversionOptions

  • ASCIIFormat: Returns MapiConversionOptions configured with OutlookMessageFormat as ASCII, with PreserveSignature set to false and UseBodyCompression set to false. This option is useful when you need a plain ASCII format conversion.

  • UnicodeFormat: Returns MapiConversionOptions with OutlookMessageFormat set to Unicode, and both PreserveSignature and UseBodyCompression set to false. Use this option for more comprehensive character support in MSG files.

  • ForcedRtfBodyForAppointment: When set to true, forces the use of RTF body for calendar appointments. This is useful if you want to ensure compatibility with certain mail clients. Default is true.

  • Format: Specifies the output format for the MSG file. It can be set to either OutlookMessageFormat.ASCII or OutlookMessageFormat.Unicode, controlling whether the converted MSG should use ASCII or Unicode encoding.

  • PreserveEmbeddedMessageFormat: Determines whether to retain the original EML format of embedded messages during conversion to MapiMessage. Setting this to true ensures that embedded emails retain their original structure. Default is false.

  • PreserveEmptyDates: When set to true, retains the original saving and modification dates from the EML. Otherwise, new dates will be generated if the original ones are empty.

  • PreserveOriginalAddresses: If set to true, maintains the original email addresses without validation. This is useful when working with email addresses that might not conform to strict standards but need to be preserved as-is. Default is false.

  • PreserveOriginalDates: Ensures the original sending and receiving dates are kept during the conversion process. Setting this to true retains these dates for better historical accuracy.

  • RemoveSignature: Controls whether the digital signature, if present, will be removed from the message during conversion. Default is false, meaning the signature will be kept unless explicitly removed.

  • UseBodyCompression: Enables RTF body compression if set to true. This can help reduce the size of the MSG file, especially when dealing with large messages with rich formatting.