Parsing .eml files in C#

I’m experimenting with importing a set of .eml files (each .eml files containing a raw email message) into a SQL database.

Producing the .eml files from an IMAP account is easy. I experimented with different tools

All of these tools are ideal for mail backup and to their job well.

Now, suppose we have a bunch of .eml files produced by one of the above mentioned backup tools. What can we do with them?

First of all, the tools that produce .eml backups, can also restore your e-mail by uploading the backed-up messages back to your IMAP account. But maybe you don’t want to store your mail backup in separate files, or encrypt the raw messages, or …fill in specific wish here... In that case you’ll want to parse the raw .eml files in your favorite language (I’ll assume here that that is C# 😉 ) so that you can do something useful with the different parts (subject, body, attachments, etc.) of the messages.

Although the .EML file format itself is not complicated (the content of an .eml file is the literal content of an e-mail message as received by a SMTP server), interpreting the content, especially MIME content, is not that easy.

Fortunately, Microsoft already implemented mail parsing for us. The method below shows how to parse a single .eml file:

protected CDO.Message ReadMessage(String emlFileName)
    CDO.Message msg = new CDO.MessageClass();
    ADODB.Stream stream = new ADODB.StreamClass();
    stream.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty);
    msg.DataSource.OpenObject(stream, "_Stream");
    return msg;

(original code from this stackoverflow topic).

You’ll need to reference the Microsoft CDO for Windows 2000 Library, which can be found on the ‘COM’ tab in the Visual Studio ‘Add reference’ dialog. The CDO library is included in IIS.

Read more

6 Responses to “Parsing .eml files in C#”

  1. ABM Abdul Muttalib says:

    Can I save as HTML format after Parsing .eml ?

  2. Ted says:

    This is not working for me, I added a reference to the Microsoft CDO for Windows 2000 Library, but it says that the CDO type or namespace cannot be found. What am I missing?

  3. ic says:

    Hi, Kindly post an example of how to use as i paste in my code but not sure how to call the method and use?

  4. ic says:

    hi, kindly post source example of how to use the script ?

  5. Hong1979 says:

    Hi admin, do you monetize your site ? There is easy method to earn decent money every day, just search on youtube – How to earn $25/hour selling articles

  1. […] A code snippet showing how to parse an .eml files with C#, using the Microsoft CDO library…. [full post] Gerwert Onderweg Blog c# .netsoftware developmentbackupcdo 0 0 0 […]

Leave a Reply

Human Verification