Loading and Parsing MSG Files
Using Aspose.Email for .NET, developers can load as well as parse contents from Outlook message files.
- To load MSG files from disk, use the static MapiMessage.Load method of the MapiMessage class. The class provides several static loading functions for different scenarios.
- To parse MSG file contents, the MapiMessage exposes a number of methods and properties.
In this article you will learn how to load and parse an MSG file to display its contents. The code samples with steps will give you a clear understanding of how to implement the functionality of loading and parsing Outlook MSG files in your project.
First, learn to load MSG files from file or from stream.
Load MSG Files
The following code snippet shows you how to load MSG files.
// Create an instance of MapiMessage from file
var msg = MapiMessage.Load(@"message.msg");
// Get subject
Console.WriteLine("Subject:" + msg.Subject);
// Get from address
Console.WriteLine("From:" + msg.SenderEmailAddress);
// Get body
Console.WriteLine("Body:" + msg.Body);
// Get recipients information
foreach (var recipient in msg.Recipients)
{
Console.WriteLine("Recipient: " + recipient.DisplayName + " <" + recipient.EmailAddress + ">");
}
// Get attachments
foreach (var att in msg.Attachments)
{
Console.Write("Attachment Name: " + att.FileName);
Console.Write("Attachment Display Name: " + att.DisplayName);
}
The following code example shows how to use MailMessage to load a message in MSG format.
var eml = MailMessage.Load("message.msg");
It should be noted that a resulting message is converted to EML format, including embedded message attachments. Don’t use this loading method if you want to preserve some specific msg format properties of the original message.
To preserve the original format of embedded message attachments, use the MsgLoadOptions.PreserveEmbeddedMessageFormat property.
var msgLoadOptions = new MsgLoadOptions();
msgLoadOptions.PreserveEmbeddedMessageFormat = true;
var msg = MailMessage.Load("message.msg", msgLoadOptions);
Load from Stream
The following code snippet shows you how to load file from stream.
// Create an instance of MapiMessage from file
byte[] bytes = File.ReadAllBytes(@"message.msg");
using (MemoryStream stream = new MemoryStream(bytes))
{
stream.Seek(0, SeekOrigin.Begin);
// Create an instance of MapiMessage from file
MapiMessage msg = MapiMessage.Load(stream);
// Get subject
Console.WriteLine("Subject:" + msg.Subject);
// Get from address
Console.WriteLine("From:" + msg.SenderEmailAddress);
// Get body
Console.WriteLine("Body:" + msg.Body);
}
Load MSG Files with Deferred Attachment Content
By default, MapiMessage.Load reads the content of every attachment into memory together with the message. For messages with large attachments, this makes the memory needed to open a message proportional to the size of its attachments, even when you only need the headers, the recipients, or the attachment names.
To leave attachment content in the source and read it only on demand, pass a MsgLoadOptions object with the following properties to the Load method:
- DeferAttachmentContent - when
true, attachment content is read from the source on demand instead of being loaded with the message. The default value isfalse. - DeferralThreshold - the minimum content size, in bytes, for which loading is deferred. Smaller attachments are always loaded with the message. The default value is 4096.
Deferred loading applies to binary attachment content. Attachments stored as OLE objects or as embedded messages are extracted when the message is loaded.
The following code sample opens a large message and lists its attachments without reading their content. The names and sizes of the attachments are available immediately:
var options = new MsgLoadOptions { DeferAttachmentContent = true };
// The file stays open until the message is disposed, so dispose the message
using (var msg = MapiMessage.Load(@"C:\data\large.msg", options))
{
Console.WriteLine($"Subject: {msg.Subject}");
Console.WriteLine($"Recipients: {msg.Recipients.Count}");
foreach (MapiAttachment attachment in msg.Attachments)
{
Console.WriteLine($" {attachment.LongFileName}: {attachment.ContentLength} bytes");
}
}
Deferred loading works well together with the MapiAttachment.OpenRead method. In the following example, only the PDF attachments are read from the file, and the content of the other attachments is never touched:
var options = new MsgLoadOptions { DeferAttachmentContent = true };
using (var msg = MapiMessage.Load(@"C:\data\large.msg", options))
{
foreach (MapiAttachment attachment in msg.Attachments)
{
if (!attachment.LongFileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
{
continue;
}
using (Stream source = attachment.OpenRead())
using (Stream target = File.Create(Path.Combine(@"C:\out", attachment.LongFileName)))
{
source.CopyTo(target);
}
}
}
The source must remain readable for as long as the message is in use:
MapiMessage.Load(string, LoadOptions)keeps the file open and closes it inDispose(). Always dispose the message, otherwise the file stays locked.MapiMessage.Load(Stream, LoadOptions)leaves the stream with the caller, who must keep it open while the message is in use.
var options = new MsgLoadOptions { DeferAttachmentContent = true };
// The caller owns the stream and must keep it open while the message is in use
using (var source = File.OpenRead(@"C:\data\large.msg"))
{
var msg = MapiMessage.Load(source, options);
var data = msg.Attachments[0].BinaryData;
Console.WriteLine($"Read {data.Length} bytes");
}
Reading deferred attachment content after the source has been closed throws an ObjectDisposedException instead of returning incomplete data.
A message can be saved back over the file it was loaded from: the message is produced in memory first, the source is released, and only then is the file overwritten. After such a save, the deferred content of the loaded message can no longer be read.
Convert EML to MSG While Preserving Embedded EML Format
EML files can be loaded into MapiMessage class by instantiating a MailMessage object and passing it to MapiMessage.FromMailMessage method. If the EML file contains embedded EML files, use MapiConversionOptions.PreserveEmbeddedMessageFormat to retain the format of embedded EML files. The below code snippet shows how to load EML files into MapiMessage while preserving the format of embedded EML files.
// Load the EML file into a MailMessage object
var mailMessage = MailMessage.Load(emlFilePath);
// Set conversion options to preserve the format of embedded EML messages
var options = new MapiConversionOptions
{
PreserveEmbeddedMessageFormat = true
};
// Convert MailMessage to MapiMessage, preserving embedded EML files
var mapiMessage = MapiMessage.FromMailMessage(mailMessage, options);
// Save the converted message in MSG format
mapiMessage.Save(msgFilePath);
Try it out!
Convert emails & message archives online with the free Aspose.Email Conversion App.
string dataDir = RunExamples.GetDataDir_Email();
var eml = MailMessage.Load(dataDir + "sample.eml", new EmlLoadOptions());
var options = MapiConversionOptions.UnicodeFormat;
//Preserve Embedded Message Format
options.PreserveEmbeddedMessageFormat = true;
//Convert EML to MSG with Options
var msg = MapiMessage.FromMailMessage(eml, options);
Parse Outlook Message Files
Aspose.Email for .NET provides the MapiMessage class that is used to open and parse an MSG file. As there may be many recipients in an MSG file, the MapiMessage class exposes the Recipients property that returns a MapiRecipientCollection which represents a collection of MapiRecipient objects. The MapiRecipient object further exposes methods for working with recipient attributes.
The following sequence of steps serves this purpose:
- Create an instance of the MapiMessage class using the MapiMessage.Load static method.
- Display the sender name, subject, and body from the MSG file using SenderName, Subject and Body properties.
- Use the Recipients property to get a reference to the collection of MapiRecipient objects associated with the MSG file.
- Loop through the MapiRecipientCollection collection to display contents for each MapiRecipient object through its public methods.
//Instantiate an MSG file to load an MSG file from disk
var outlookMessageFile = MapiMessage.Load(dataDir + "message.msg");
//Display sender's name
Console.WriteLine("Sender Name : " + outlookMessageFile.SenderName);
//Display Subject
Console.WriteLine("Subject : " + outlookMessageFile.Subject);
//Display Body
Console.WriteLine("Body : " + outlookMessageFile.Body);
//Display Recipient's info
Console.WriteLine("Recipients : \n");
//Loop through the recipients collection associated with the MapiMessage object
foreach (var rcp in outlookMessageFile.Recipients)
{
//Display recipient email address
Console.WriteLine("Email : " + rcp.EmailAddress);
//Display recipient name
Console.WriteLine("Name : " + rcp.DisplayName);
//Display recipient type
Console.WriteLine("Recipient Type : " + rcp.RecipientType);
}
Try it out!
Parse email files online with the free Aspose.Email Parser App.