How to Read MSG Files in C#

How to Read MSG Files in C#

This guide shows how to open an Outlook .msg file and extract its contents using Aspose.Email FOSS for .NET. You will access the subject, body, sender, recipients, and attachment list using MapiMessage. The library supports loading from a file path, a Stream, or a raw byte[].

Step 1 — Install the Package

Install the Aspose.Email FOSS package from NuGet using the .NET CLI command below:

dotnet add package Aspose.Email.Foss

Step 2 — Load the MSG File

Call MapiMessage.FromFile() with the path to the .msg file to load it into a disposable MapiMessage instance:

using Aspose.Email.Foss.Msg;

using var message = MapiMessage.FromFile("sample.msg");

To load from an existing Stream instead of a file path, use the MapiMessage.FromStream() overload:

using var stream = File.OpenRead("sample.msg");
using var message = MapiMessage.FromStream(stream);

Step 3 — Read Message Fields

Access Subject, SenderName, SenderEmailAddress, MessageDeliveryTime, and Body as plain properties on the loaded message:

Console.WriteLine($"Subject: {message.Subject}");
Console.WriteLine($"From: {message.SenderName} <{message.SenderEmailAddress}>");
Console.WriteLine($"Date: {message.MessageDeliveryTime}");
Console.WriteLine($"Body: {message.Body}");

Step 4 — Read Recipients

Enumerate message.Recipients to access each recipient’s DisplayName and EmailAddress:

foreach (var recipient in message.Recipients)
{
    Console.WriteLine($"{recipient.DisplayName} <{recipient.EmailAddress}>");
}

Step 5 — Extract Attachments

Enumerate message.Attachments and call File.WriteAllBytes() with attachment.Filename and attachment.Data to save each file:

foreach (var attachment in message.Attachments)
{
    Console.WriteLine($"Saving: {attachment.Filename}");
    File.WriteAllBytes(attachment.Filename!, attachment.Data);
}

To access an MSG embedded as an attachment, check IsEmbeddedMessage and read the nested EmbeddedMessage property:

foreach (var attachment in message.Attachments)
{
    if (attachment.IsEmbeddedMessage)
    {
        Console.WriteLine($"Embedded: {attachment.EmbeddedMessage!.Subject}");
    }
}

Complete Example

The following runnable example combines all steps — loading, reading fields, iterating recipients, and saving or listing attachments:

using Aspose.Email.Foss.Msg;

using var message = MapiMessage.FromFile("sample.msg");

Console.WriteLine($"Subject: {message.Subject}");
Console.WriteLine($"From: {message.SenderName} <{message.SenderEmailAddress}>");

foreach (var r in message.Recipients)
    Console.WriteLine($"  {r.DisplayName} <{r.EmailAddress}>");

foreach (var a in message.Attachments)
{
    if (a.IsEmbeddedMessage)
        Console.WriteLine($"  Embedded: {a.EmbeddedMessage!.Subject}");
    else
        File.WriteAllBytes(a.Filename!, a.Data);
}

See Also

 English