Click here to Skip to main content
15,881,089 members
Articles / Productivity Apps and Services / Microsoft Office

Reading an Outlook MSG File in C#

Rate me:
Please Sign up or sign in to vote.
4.88/5 (116 votes)
8 Jul 2010CPOL3 min read 1.3M   28.4K   190   290
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.

C#
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.

C#
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)


Written By
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

 
AnswerRe: Attachments in a digitally signed email Pin
Almutalibi, Mohamad2-Mar-10 4:42
Almutalibi, Mohamad2-Mar-10 4:42 
AnswerRe: Attachments in a digitally signed email Pin
Ian A Davidson4-May-10 3:13
Ian A Davidson4-May-10 3:13 
AnswerRe: Attachments in a digitally signed email, EDIT: How about the Body Text? Pin
Constantine_Rex20-Mar-11 2:28
Constantine_Rex20-Mar-11 2:28 
GeneralRe: Attachments in a digitally signed email, EDIT: How about the Body Text? Pin
Ian A Davidson3-Jul-12 23:58
Ian A Davidson3-Jul-12 23:58 
GeneralRe: Attachments in a digitally signed email, EDIT: How about the Body Text? Pin
Constantine_Rex7-Nov-12 16:20
Constantine_Rex7-Nov-12 16:20 
QuestionCOM object disconnects Pin
Midi_Mick16-Mar-09 19:42
professionalMidi_Mick16-Mar-09 19:42 
AnswerRe: COM object disconnects Pin
Midi_Mick19-Mar-09 18:20
professionalMidi_Mick19-Mar-09 18:20 
GeneralRe: COM object disconnects Pin
David Ewen19-Mar-09 18:39
professionalDavid Ewen19-Mar-09 18:39 
Thank you, I was just looking at this myself and almost at the same spot.

To be complete leaving the Marshal.ReleaseComObject(this.storage) in the finalizer and just suppressing it for the temporary object in the constructor of the recipient and attachment classes will allow the Dispose function to completely free unmanaged resources as expected.

public Recipient(OutlookStorage message): base(message.storage)
{
    GC.SuppressFinalize(message);
    this.propHeaderSize = OutlookStorage.PROPERTIES_STREAM_HEADER_ATTACH_OR_RECIP;
}


public Attachment(OutlookStorage message): base(message.storage)
{
    GC.SuppressFinalize(message);
    this.propHeaderSize = OutlookStorage.PROPERTIES_STREAM_HEADER_ATTACH_OR_RECIP;
}

GeneralRe: COM object disconnects Pin
Midi_Mick19-Mar-09 19:10
professionalMidi_Mick19-Mar-09 19:10 
GeneralRe: COM object disconnects Pin
mel250622-Dec-09 23:20
mel250622-Dec-09 23:20 
AnswerRe: COM object disconnects Pin
Midi_Mick23-Dec-09 11:57
professionalMidi_Mick23-Dec-09 11:57 
GeneralRaceOnRCWCleanup was detected (in OutlookStorage.Dispose) Pin
scott.leckie27-Feb-09 14:07
scott.leckie27-Feb-09 14:07 
GeneralRe: RaceOnRCWCleanup was detected (in OutlookStorage.Dispose) [Resolved] Pin
scott.leckie28-Feb-09 13:46
scott.leckie28-Feb-09 13:46 
GeneralSpecial characters Pin
johncage4025-Feb-09 5:18
johncage4025-Feb-09 5:18 
GeneralRe: Special characters Pin
David Ewen25-Feb-09 17:16
professionalDavid Ewen25-Feb-09 17:16 
GeneralRe: Special characters Pin
johncage4026-Feb-09 0:37
johncage4026-Feb-09 0:37 
QuestionHow to get attached file complete path in Outlook 2003 Addin Pin
alimurtaz23-Feb-09 20:53
alimurtaz23-Feb-09 20:53 
AnswerRe: How to get attached file complete path in Outlook 2003 Addin Pin
Midi_Mick25-Feb-09 15:54
professionalMidi_Mick25-Feb-09 15:54 
QuestionHow to get the PR_ENTRYID value? Pin
Test554302123-Feb-09 2:37
Test554302123-Feb-09 2:37 
AnswerRe: How to get the PR_ENTRYID value? Pin
David Ewen25-Feb-09 17:10
professionalDavid Ewen25-Feb-09 17:10 
GeneralExcellent Pin
scott.leckie23-Feb-09 1:28
scott.leckie23-Feb-09 1:28 
QuestionHow to get received date? Pin
johncage4019-Feb-09 0:06
johncage4019-Feb-09 0:06 
AnswerRe: How to get received date? PinPopular
David Ewen19-Feb-09 14:38
professionalDavid Ewen19-Feb-09 14:38 
GeneralRe: How to get received date? Pin
subri719-Mar-09 3:43
subri719-Mar-09 3:43 
GeneralRe: How to get received date? Pin
David Ewen19-Mar-09 17:19
professionalDavid Ewen19-Mar-09 17:19 

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.