Saturday, November 20, 2010

Reading EML files

You can do this 'properly' (certainly better than trying to parse it as a text file) by using the COM cdosys.dll ('Microsoft CDO for Windows 2000 Library').

You'll need to create a .Net wrapper for it by adding a reference: because it depends on ADODB.dll, you'll get Interop.CDO.dll and Interop.ADODB.dll created for you in your bin directory.

There's a lot of information around for sending emails using CDO but almost nothing about using it to read EML files, but I found this page that got me started with iterating through and reading all the eml files in a mailbox directory (like inetpub\mailroot\mailbox\xxx.domain.com\) http://support.microsoft.com/kb/310224

If what you want to do is just open a specific eml file (that you already know the filename of) then there's another way to do it: http://stackoverflow.com/questions/936422/recommendations-on-parsing-eml-files-in-c

 Public Shared Function getEmlFileAsMessage(ByVal path As String) As Object
        Dim msg As CDO.Message = New CDO.MessageClass()
        Dim stream As ADODB.Stream = New ADODB.StreamClass()
        Try
            stream.Open(Type.Missing, ADODB.ConnectModeEnum.adModeUnknown, ADODB.StreamOpenOptionsEnum.adOpenStreamUnspecified, String.Empty, String.Empty)
            stream.LoadFromFile(path)
            stream.Flush()
            msg.DataSource.OpenObject(stream, "_Stream")
            msg.DataSource.Save()
            Return msg
        Catch
            Return Nothing
        End Try

    End Function