This technical tip explains how to load a Microsoft Outlook Messagefile (*.msg). The MapiMessage class is used to load MSG files, and provides several static loading functions for different scenarios. The code samples below show how to load MSG files from file or from stream. Some important steps for performing this task are Create an instance of MapiMessage from file, Get subject, Get from address, Get message body and Get attachments.

Sample Code for Outlook Message (MSG) File Loading, Viewing and Parsing

Loading MSG Files


[C#]

Code:
//Create an instance of MapiMessage from file
MapiMessagemsg = MapiMessage.FromFile(@"d:\Test.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
Console.WriteLine("Recipient: " + msg.Recipients);

//Get attachments
foreach (MapiAttachmentatt in msg.Attachments)
{
Console.Write("Attachment Name: " + att.FileName);
Console.Write("Attachment Display Name: " + att.DisplayName);
}

[VB.NET]
Code:
'Create an instance of MapiMessage from file
Dim msg As MapiMessage = MapiMessage.FromFile("d:\Test.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
Console.WriteLine("Recipient: " &msg.Recipients.ToString())

'Get attachments
For Each att As MapiAttachment In msg.Attachments
Console.Write("Attachment Name: " &att.FileName)
Console.Write("Attachment Display Name: " &att.DisplayName)
Next att
Loading MSG files from Stream

[C#]

Code:
byte[] bytes = System.IO.File.ReadAllBytes(@"c:\test.msg");

using (MemoryStream stream =
newSystem.IO.MemoryStream(bytes))
{
stream.Seek(0, System.IO.SeekOrigin.Begin);
    //Create an instance of MapiMessage from file
MapiMessagemsg = MapiMessage.FromStream(stream);

    //Get subject
Console.WriteLine("Subject:" + msg.Subject);

    //Get from address
Console.WriteLine("From:" + msg.SenderEmailAddress);

    //Get body
Console.WriteLine("Body" + msg.Body);

}
[VB.NET]

Code:
Dim bytes() As Byte = System.IO.File.ReadAllBytes("c:\test.msg")

Dim stream As MemoryStream = New System.IO.MemoryStream(bytes)

stream.Seek(0, System.IO.SeekOrigin.Begin)
'Create an instance of MapiMessage from file
Dim msg As MapiMessage = MapiMessage.FromStream(stream)

'Get subject
Console.WriteLine("Subject:" + msg.Subject)

'Get from address
Console.WriteLine("From:" + msg.SenderEmailAddress)

'Get body
Console.WriteLine("Body" + msg.Body)