DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Sheraz has posted 65 posts at DZone. View Full User Profile

Load, Parse or View MS Outlook MSG Files from a File or Stream

05.29.2013
| 3561 views |
  • submit to reddit
//Loading MSG Files

//[C#]

//Create an instance of MapiMessage from file
MapiMessage msg = 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 (MapiAttachment att in msg.Attachments)
{
    Console.Write("Attachment Name: " + att.FileName);
    Console.Write("Attachment Display Name: " + att.DisplayName);
}


[VB.NET]

'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#]

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

using (MemoryStream stream =
        new System.IO.MemoryStream(bytes))
{
    stream.Seek(0, System.IO.SeekOrigin.Begin);
    //Create an instance of MapiMessage from file
    MapiMessage msg = 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]

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)
This technical tip explains how to load a Microsoft Outlook Messagefile (*.msg). The MapiMessage class is used to load Outlook 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.