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

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mail = MailMessage.Load(dataDir + "tnefWithMsgInside.eml", new EmlLoadOptions() { PreserveEmbeddedMessageFormat = true });
FileFormatType fileFormat = FileFormatUtil.DetectFileFormat(mail.Attachments[0].ContentStream).FileFormatType;
Console.WriteLine("Embedded message file format: " + fileFormat);

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.

// 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();
// Detect file format and Gets the detected load format
FileFormatInfo info = FileFormatUtil.DetectFileFormat(dataDir + "message.msg");
Console.WriteLine("The message format is: " + info.FileFormatType);

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.

// 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();
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage mailMessage = MailMessage.Load(dataDir + "Attachments.eml");
mailMessage.Save(dataDir + "LoadAndSaveFileAsEML_out.eml", SaveOptions.DefaultEml);

Preserve the Original Boundaries

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

// 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 mailMessage = MailMessage.Load(dataDir + "Attachments.eml");
// Save as eml with preserved original boundares
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
PreserveOriginalBoundaries = true
};
mailMessage.Save(dataDir + "PreserveOriginalBoundaries_out.eml", emlSaveOptions);

Preserve TNEF Attachments

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

// 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 mailMessage = MailMessage.Load(dataDir + "PreserveOriginalBoundaries.eml");
// Save as eml with preserved attachment
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
FileCompatibilityMode = FileCompatibilityMode.PreserveTnefAttachments
};
mailMessage.Save(dataDir + "PreserveTNEFAttachment_out.eml", emlSaveOptions);

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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Data directory for reading and writing files
string dataDir = RunExamples.GetDataDir_Email();
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
// Save the Email message to disk in ASCII format and Unicode format
eml.Save(dataDir + "AnEmail_out.msg", SaveOptions.DefaultMsgUnicode);

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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
// Data directory for reading and writing files
string dataDir = RunExamples.GetDataDir_Email();
// Initialize and Load an existing EML file by specifying the MessageFormat
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
// Save as msg with preserved dates
MsgSaveOptions msgSaveOptions = new MsgSaveOptions(MailMessageSaveType.OutlookMessageFormatUnicode)
{
PreserveOriginalDates = true
};
eml.Save(Path.Combine(dataDir, "outTest_out.msg"), msgSaveOptions);

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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(Path.Combine(dataDir, "Message.eml"));
// Save as mht with header
MhtSaveOptions mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to outpu without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
eml.Save(Path.Combine(dataDir, "outMessage_out.mht"), mhtSaveOptions);

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.

// 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();
string fileName = "Meeting with Recurring Occurrences.msg";
MailMessage msg = MailMessage.Load(dataDir + fileName);
MhtSaveOptions options = new MhtSaveOptions();
{
options.MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.RenderCalendarEvent;
//Format the output details if required - optional
//Set the display for Start Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.Start))
options.FormatTemplates[MhtTemplateName.Start] = @"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.Start, @"<span class='headerLineTitle'>Start:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for End Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.End))
options.FormatTemplates[MhtTemplateName.End] = @"<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.End, @"<span class='headerLineTitle'>End:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Recurrence Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.Recurrence))
options.FormatTemplates[MhtTemplateName.Recurrence] = @"<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.Recurrence, @"<span class='headerLineTitle'>Recurrence:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RecurrencePattern Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.RecurrencePattern))
options.FormatTemplates[MhtTemplateName.RecurrencePattern] = @"<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.RecurrencePattern, @"<span class='headerLineTitle'>RecurrencePattern:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for Organizer Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.Organizer))
options.FormatTemplates[MhtTemplateName.Organizer] = @"<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.Organizer, @"<span class='headerLineTitle'>Organizer:</span><span class='headerLineText'>{0}</span><br/>");
//Set the display for RequiredAttendees Property
if (options.FormatTemplates.ContainsKey(MhtTemplateName.RequiredAttendees))
options.FormatTemplates[MhtTemplateName.RequiredAttendees] = @"<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>";
else
options.FormatTemplates.Add(MhtTemplateName.RequiredAttendees, @"<span class='headerLineTitle'>RequiredAttendees:</span><span class='headerLineText'>{0}</span><br/>");
};
msg.Save(dataDir + "Meeting with Recurring Occurrences.mhtml", options);

Exporting Email to MHT without Inline Images

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
mhtSaveOptions.SkipInlineImages = true;
eml.Save(Path.Combine(dataDir, "EmlToMhtmlWithoutInlineImages_out.mht"), mhtSaveOptions);

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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
// Set the local time for message date.
eml.TimeZoneOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
// or set custom time zone offset for message date (-0800)
// eml.TimeZoneOffset = new TimeSpan(-8,0,0);
// The dates will be rendered by local system time zone.
MhtSaveOptions so = new MhtSaveOptions();
so.MhtFormatOptions = MhtFormatOptions.WriteHeader;
eml.Save(dataDir + "ExportEmailToMHTWithCustomTimezone_out.mhtml", so);

Font Adjustment

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
string dataDir = RunExamples.GetDataDir_Email();
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
MhtSaveOptions options = SaveOptions.DefaultMhtml;
int cssInsertPos = options.CssStyles.LastIndexOf("</style>");
options.CssStyles = options.CssStyles.Insert(cssInsertPos,
".PlainText{" +
" font-family: sans-serif;" +
"}"
);
eml.Save("message.mhtml", options);

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.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
MailMessage message = MailMessage.Load(dataDir + "Message.eml");
message.Save(dataDir + "SaveAsHTML_out.html", SaveOptions.DefaultHtml);
// OR
MailMessage eml = MailMessage.Load(dataDir + "Message.eml");
HtmlSaveOptions options = SaveOptions.DefaultHtml;
options.EmbedResources = false;
options.HtmlFormatOptions = HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress; //save the message headers to output HTML using the formatting options
eml.Save(dataDir + "SaveAsHTML1_out.html", options);

Save without Embedded Resources

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
var fileName = "EmailWithAttandEmbedded.eml";
var filePath = Path.Combine(dataDir, fileName);
MailMessage msg = MailMessage.Load(filePath);
var outFileName = Path.Combine(dataDir, fileName + ".html");
var options = new HtmlSaveOptions()
{
EmbedResources = false,
SaveResourceHandler =
(AttachmentBase attachment, out string resourcePath) =>
{
attachment.Save(Path.Combine(dataDir, attachment.ContentId));
resourcePath = Path.Combine(".", attachment.ContentId);
}
};
msg.Save(outFileName, options);

Save EML to OFT

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

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (MailMessage eml = new MailMessage("test@from.to", "test@to.to", "template subject", "Template body"))
{
string oftEmlFileName = "EmlAsOft_out.oft";
MsgSaveOptions options = SaveOptions.DefaultMsgUnicode;
options.SaveAsTemplate = true;
eml.Save(dataDir + oftEmlFileName, options);
}

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.