Click or drag to resize

Parsing messages

One of the more common operations that MimeKit is meant for is parsing email messages from arbitrary streams. There are two ways of accomplishing this task.

This topic contains the following sections:

Using the Load methods

The easiest way is to use one of the Load methods on MimeMessage.

// Load a MimeMessage from a stream
var message = MimeMessage.Load (stream);
Using MimeParser directly

The second way is to use the MimeParser class. For the most part, using the MimeParser directly is not necessary unless you wish to parse a Unix mbox file stream. However, this is how you would do it:

public static MimeMessage ParseMessage (string fileName)
    // Load a MimeMessage from a file path or stream
    using (var stream = File.OpenRead (fileName)) {
        var parser = new MimeParser (stream, MimeFormat.Entity);

        return parser.ParseMessage ();

For Unix mbox file streams, you would use the parser like this:

public static void ParseMbox (string fileName)
    // Load every message from a Unix mbox spool.
    using (var stream = fileName.OpenRead (fileName)) {
        var parser = new MimeParser (stream, MimeFormat.Mbox);

        while (!parser.IsEndOfStream) {
            MimeMessage message = parser.ParseMessage ();
            long mboxMarkerOffset = parser.MboxMarkerOffset;
            string mboxMarker = parser.MboxMarker;

            Console.WriteLine ($"MBOX marker found @ {mboxMarkerOffset}: {mboxMarker}");

            // TODO: Do something with the message.
See Also