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

dotnet add package Aspose.Email.Foss

Step 2 — Load the MSG File

using Aspose.Email.Foss.Msg;

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

You can also load from a stream:

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

Step 3 — Read Message Fields

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

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

Step 5 — Extract Attachments

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

For embedded message attachments:

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

Complete Example

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