Click here to Skip to main content
14,302,017 members

Reading an Outlook MSG File in C#

Rate this:
4.88 (114 votes)
Please Sign up or sign in to vote.
4.88 (114 votes)
8 Jul 2010CPOL
How to read an Outlook msg file in C# without the Outlook object model
Demo application form

Introduction

This article is going to focus on how to dissect a msg file generated by Outlook. It covers how to read the basic properties of the mail message, attachments and any msg attachments (these need to be handled differently).

Using the Code

The code is pretty simple to use. You construct a new instance of the OutlookStorage.Message class, sending it the path to a msg file or a Stream containing an IStorage. The Stream constructor is provided so that it is easy to integrate with the Outlook drag and drop code in another of my articles and this is shown in the demo application.

private static void main()
{
    //create new Outlook message from file
    OutlookStorage.Message outlookMsg = new OutlookStorage.Message(@"C:\test.msg");
    DisplayMessage(outlookMsg);
}

private static void DisplayMessage(OutlookStorage.Message outlookMsg)
{    
    Console.WriteLine("Subject: {0}", outlookMsg.Subject);
    Console.WriteLine("Body: {0}", outlookMsg.BodyText);
    
    Console.WriteLine("{0} Recipients", outlookMsg.Recipients.Count);    
    foreach (OutlookStorage.Recipient recip in outlookMsg.Recipients)
    {
        Console.WriteLine(" {0}:{1}", recip.Type, recip.Email);
    }
    
    Console.WriteLine("{0} Attachments", outlookMsg.Attachments.Count);
    foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
    {
        Console.WriteLine(" {0}, {1}b", attach.Filename, attach.Data.Length);
    }

    Console.WriteLine("{0} Messages", outlookMsg.Messages.Count);
    foreach (OutlookStorage.Message subMessage in outlookMsg.Messages)
    {
        DisplayMessage(subMessage);
    }
}

Save a Msg and All Attachments to the File System

This is an example on how to save a message and all associated attachments to the application path.

private static void main()
{
    //create new Outlook message from file
    OutlookStorage.Message outlookMsg = new OutlookStorage.Message(@"C:\test.msg");
}

private static void SaveMessage(OutlookStorage.Message outlookMsg)
{    
    outlookMsg.Save(outlookMsg.Subject.Replace(":", ""));    

    foreach (OutlookStorage.Attachment attach in outlookMsg.Attachments)
    {
        byte[] attachBytes = attach.Data;
        FileStream attachStream = File.Create(attach.Filename);
        attachStream.Write(attachBytes, 0, attachBytes.Length);
        attachStream.Close();
    }

    foreach (OutlookStorage.Message subMessage in outlookMsg.Messages)
    {
        SaveMessage(subMessage);
    }
}

Understanding the Code

To read the msg file produced by Outlook, there are two concepts to understand. The first is that an msg file is logically a MAPI object with MAPI properties and the second is that phyiscally the MAPI object and its properties are stored in an IStorage. Microsoft has kindly provided a specification on how the MAPI properties are mapped to the IStorage, so at this point I will defer to that and just go over the catches that popped up when figuring out how to save a sub message out of its parent.

Saving a Sub Message

Saving a sub message out of the parent message has a few catches. The property stream header needs to be padded and the name to id mapping storage needs to be copied to the sub message storage.

Fixing the Property Stream

MAPI property values can be stored in a sub storage, a sub stream or in the case of fixed size values (like an integer) a special sub stream called the property stream. The property stream consists of a variable length header and then an array of 16 byte pairs with a property identifier in the first 8 bytes and the property value in the second 8.

It is the variable length header that you should take note of. It is 8 bytes for an attachment or recipient storage, 32 bytes for a top level msg and 24 bytes for a sub msg. This means that if you want to extract a sub message and save it without its parent you need to pad the end of the header with 8 null bytes.

The Name to Id Mapping

The other catch for saving a sub message is the name to id mapping storage which only exists on the top level msg, but contains the mappings for the entire tree. So when saving a sub message, this storage needs to be copied to it before saving for it to be valid.

Conclusion

Everything is encapsulated in the OutlookStorage.cs file as I don't like to release stuff with dependencies and prefer to just be able to drop a CS into my projects to get a particular piece of functionality. There is a region in there under a separate licence for the code to decompress the compressed RTF, but it is clearly marked.

History

  • 8th July, 2010
    • Fixed memory leak
    • Fixed the "COM object that has been separated from its underlying RCW cannot be used" exception
    • Added better determination of attachment file name
  • 28th January, 2009: Original article

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

David Ewen
Founder Guava Development
Australia Australia
I am the Founder of Guava Development a Software Services Company located in Perth, Western Australia dedicated to improving productivity and reducing costs through the targeted and innovative application of software assisted workflows and packages.

I have been working in the industry for 10 years. My day job usually involves programming with C# but I have been known to mess around with just about everything.

Comments and Discussions

 
PraiseGreat Job! Pin
Burak Cucu1-Sep-19 17:57
memberBurak Cucu1-Sep-19 17:57 
GeneralMy vote of 5 Pin
asimonassi14-Jan-19 22:44
memberasimonassi14-Jan-19 22:44 
Question.MSGs attached to .MSG Pin
Member 139453606-Sep-18 8:40
memberMember 139453606-Sep-18 8:40 
AnswerRe: .MSGs attached to .MSG Pin
AnUj VIkal18-Nov-18 19:29
memberAnUj VIkal18-Nov-18 19:29 
Questioninline attachement and regular attachement Pin
Member 1229809513-Sep-17 1:39
memberMember 1229809513-Sep-17 1:39 
QuestionNeed to Save the message file without any attachment Pin
Biswojit Kumar Sahu15-Feb-17 3:42
professionalBiswojit Kumar Sahu15-Feb-17 3:42 
QuestionHow we can Get The Message Type? Pin
Salman Mustansar20-Nov-16 13:36
memberSalman Mustansar20-Nov-16 13:36 
QuestionHow do you access other properties such as PR_ENTRYID? Pin
TheMffnMan24-Oct-16 9:47
memberTheMffnMan24-Oct-16 9:47 
QuestionOut of date Pin
EmilioNT15-Oct-15 6:10
memberEmilioNT15-Oct-15 6:10 
AnswerRe: Out of date Pin
Kees van Spelde22-Jun-16 1:48
professionalKees van Spelde22-Jun-16 1:48 
GeneralMy vote of 5 Pin
PravinSingh10-Mar-15 7:10
memberPravinSingh10-Mar-15 7:10 
QuestionFrom email address? Pin
Geoff Hudik17-Nov-14 11:15
memberGeoff Hudik17-Nov-14 11:15 
AnswerRe: From email address? Pin
Geoff Hudik17-Nov-14 12:27
memberGeoff Hudik17-Nov-14 12:27 
GeneralRe: From email address? Pin
Kees van Spelde15-Dec-14 5:58
professionalKees van Spelde15-Dec-14 5:58 
QuestionObject Reference Not Set storage.EnumElements Pin
Geoff Hudik17-Nov-14 10:45
memberGeoff Hudik17-Nov-14 10:45 
AnswerRe: Object Reference Not Set storage.EnumElements Pin
Geoff Hudik17-Nov-14 11:13
memberGeoff Hudik17-Nov-14 11:13 
GeneralRe: Object Reference Not Set storage.EnumElements Pin
Kees van Spelde15-Dec-14 5:59
professionalKees van Spelde15-Dec-14 5:59 
QuestionHow to get the date the email was sent ? Pin
Liran Friedman17-Nov-14 2:12
memberLiran Friedman17-Nov-14 2:12 
AnswerRe: How to get the date the email was sent ? Pin
Member 81816787-Dec-14 0:09
memberMember 81816787-Dec-14 0:09 
GeneralRe: How to get the date the email was sent ? Pin
Kees van Spelde15-Dec-14 5:59
professionalKees van Spelde15-Dec-14 5:59 
GeneralRe: How to get the date the email was sent ? Pin
Delphi.7.Solutions12-Mar-18 6:28
memberDelphi.7.Solutions12-Mar-18 6:28 
QuestionHow can we identify the draft email Pin
akashkarda8-Oct-14 9:31
memberakashkarda8-Oct-14 9:31 
GeneralMy vote of 5 Pin
Andy Roberts31-May-14 9:05
memberAndy Roberts31-May-14 9:05 
GeneralRe: My vote of 5 Pin
Kees van Spelde4-Nov-14 7:38
professionalKees van Spelde4-Nov-14 7:38 
QuestionWorks great until I try to read a recipient that has an underscore in their e-mail address Pin
Member 1068027621-Mar-14 7:36
memberMember 1068027621-Mar-14 7:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Article
Posted 28 Jan 2009

Stats

959.1K views
24.4K downloads
187 bookmarked