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.
- Initialize an instance of EmlLoadOptions.
- Configure the load options as needed.
- 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
- PreferredTextEncoding: Sets the preferred encoding for the message subject and body. Default is
null. - PreserveEmbeddedMessageFormat: Indicates whether to preserve the format of embedded messages during loading. Default is
false. - PreserveTnefAttachments: Controls TNEF attachment loading behavior. Default is
false. - RemoveSignature: Specifies whether the signature should be removed while loading. Default is
false.
Preserve Embedded Message Format
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 = MailMessage.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.
- Instantiate the EmlxLoadOptions.
- Configure properties as necessary.
- 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
- 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.
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.
- Initialize an instance of HtmlLoadOptions.
- Configure the necessary properties.
- 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
- PathToResources: Defines the path to the directory containing resource files (images, for ex.).
- PreferredTextEncoding: Sets the preferred encoding for message subject and body. Default is
null. - PreserveEmbeddedMessageFormat: Determines whether to preserve the format of embedded messages. Default is
false. - ShouldAddPlainTextView: Specifies whether to add a plain text view of the message body. Default is
false.
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.
- Create an instance of MhtmlLoadOptions.
- Configure the desired properties.
- 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
- MessageFormat: Represents the mail message format, which can be EML, MSG, or MHTML. Default is EML.
- PreferredTextEncoding: Sets preferred encoding for message subject and body. Default is
null. - PreserveEmbeddedMessageFormat: Determines whether to preserve the format of embedded messages. Default is
false. - PreserveTnefAttachments: Controls TNEF attachment loading behavior. Default is
false. - RemoveSignature: Specifies whether to remove the signature during loading. Default is
false.
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.
- Create an instance of MsgLoadOptions.
- Set the desired properties to customize loading.
- 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
- KeepOriginalEmailAddresses: Indicates whether to keep original email addresses. Default is
false. - PreferredTextEncoding: Defines the preferred encoding for message subject and body. Default is
null. - PreserveEmbeddedMessageFormat: Determines if the format of embedded messages should be preserved. Default is
false. - PreserveRtfContent: Specifies whether to keep RTF body content in the
MailMessage. Default isfalse. - PreserveTnefAttachments: Manages TNEF attachment loading behavior. Default is
false. - RemoveSignature: Decides whether to remove the signature during loading. Default is
false. - Timeout: Limits the formatting time in milliseconds during conversion. Default is 3000 ms.
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.
- Instantiate the TnefLoadOptions.
- Configure the properties as needed.
- 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.
Load a Message from a Microsoft SharePoint Document Library
You can read email messages stored in a Microsoft SharePoint document library and load them into a MailMessage object. To access files in a SharePoint document library, the SharePoint SDK must be installed on the system. The SDK provides the API necessary to log in and access files from the document library.
The example below assumes that a Microsoft Outlook message file (.msg) is already stored in the Shared Documents folder of the SharePoint document library. The SharePoint SDK is used to read the message file into a stream, which is then passed to the MailMessage.Load method. Once loaded, the message properties (subject, text body, HTML body, etc.) can be accessed. For information on how to install and configure Microsoft SharePoint Server and the SDK, please refer to the respective sections in the MSDN library.
// Private members
private SPSite site = null;
private SPWeb web = null;
private void EstablishSharepoint()
{
site = new SPSite("http://localhost/Site1");
web = site.OpenWeb();
}
private void button2_Click(object sender, EventArgs e)
{
SPSecurity.CodeToRunElevated elevatedGetSite = new SPSecurity.CodeToRunElevated(EstablishSharepoint);
SPSecurity.RunWithElevatedPrivileges(elevatedGetSite);
// Path to the MSG file stored in the Shared Documents folder
SPFile msgFile = web.GetFile("Shared Documents/Test.msg");
// Read the file into a memory stream
MemoryStream fileStream = new MemoryStream();
byte[] currentFileContent = msgFile.OpenBinary();
fileStream.Write(currentFileContent, 0, currentFileContent.Length);
fileStream.Position = 0;
// Create an instance of the MailMessage class and pass the memory stream of the MSG file to it
MailMessage msg = MailMessage.Load(fileStream, new MsgLoadOptions());
fileStream.Close();
fileStream.Dispose();
// Access the MailMessage class' public properties
Console.WriteLine("Subject: " + msg.Subject);
Console.WriteLine("From: " + msg.From.ToString());
Console.WriteLine("Text Body: " + msg.TextBody);
}
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 types and methods can be used to detect the loaded file format.
- FileFormatType Enumeration
- FileFormatInfo Class
- FileFormatUtil Class
- FileFormatUtil.DetectFileFormat(Stream) Method
- FileFormatUtil.DetectFileFormat(String) Method
The following code snippet shows you how to detect file formats.
// 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 save it to the disc in the same format.
// 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);
Boundaries of the Original Message
When an EML message is loaded and saved back to EML, the boundaries of the source message are preserved by default, so no configuration is required to keep them. Earlier versions of the library exposed an EmlSaveOptions.PreserveOriginalBoundaries property for this purpose. That property has been removed, and preserving the original boundaries is now the default behavior.
Customize the MIME Boundaries
If you need the boundaries to follow a specific pattern instead, use the BoundariesTemplate property of the EmlSaveOptions class. It defines the template used to generate MIME boundaries for the saved message. The default value is null, which means the boundaries are generated by the library. Two wildcards are supported in the template:
{#}– the boundary number.{guid}– a generated GUID.
The following code snippet shows you how to load EML and save it as EML with custom MIME boundaries.
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mailMessage = MailMessage.Load(dataDir + "Attachments.eml");
// Save as eml with a custom boundary template
EmlSaveOptions emlSaveOptions = new EmlSaveOptions(MailMessageSaveType.EmlFormat)
{
BoundariesTemplate = "boundary_{#}_{guid}"
};
mailMessage.Save(dataDir + "CustomBoundaries_out.eml", emlSaveOptions);
Preserve TNEF Attachments
The following code snippet shows you how to save as EML preserving TNEF attachments.
// The path to the File directory.
string dataDir = RunExamples.GetDataDir_Email();
MailMessage mailMessage = MailMessage.Load(dataDir + "tnefEML.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.
// 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.
// 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.
// 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– skip the Byte Order Mark (BOM) bytes in the body of 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.
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 information to the output 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.
// 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
The SkipInlineImages property of the MhtSaveOptions class defines whether to skip the references to images when saving to MHTML. The default value is false.
MailMessage eml = MailMessage.Load(Path.Combine(dataDir, "Message.eml"));
MhtSaveOptions mhtSaveOptions = new 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.
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
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.
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.HtmlFormatOptions = HtmlFormatOptions.WriteHeader | HtmlFormatOptions.WriteCompleteEmailAddress; //save the message headers to output HTML using the formatting options
eml.Save(dataDir + "SaveAsHTML1_out.html", options);
Control How Resources Are Rendered
The ResourceRenderingMode property of the HtmlSaveOptions class defines how message resources (inline images, for example) are written to the output HTML. It accepts the values of the ResourceRenderingMode enumeration:
EmbedIntoHtml– embed the resources into the HTML as base64 strings. This is the default value.SaveToFile– save the resources to files and insert the path to each file into thesrctag.SubstituteFromFile– use a custom file as an icon and insert the path to it into thesrctag.None– do not render the resources in the HTML.
When the resources are not embedded, the SaveResourceHandler delegate is called for every message attachment, which lets you decide where each resource is stored and which path is written to the HTML.
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()
{
ResourceRenderingMode = ResourceRenderingMode.SaveToFile,
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.
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.
- Create an instance of
MapiConversionOptionsand configure its properties. - Convert the
MailMessageobject to aMapiMessageobject 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
MapiConversionOptionsconfigured withOutlookMessageFormatas ASCII, withPreserveSignatureset to false andUseBodyCompressionset to false. This option is useful when you need a plain ASCII format conversion. -
UnicodeFormat: Returns
MapiConversionOptionswithOutlookMessageFormatset to Unicode, and bothPreserveSignatureandUseBodyCompressionset 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.ASCIIorOutlookMessageFormat.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.