This article demonstrates how to upload an EML file into a Microsoft .NET
MailMessage. This supercedes other work I have written on this. I had trouble with the other method not decoding the message's HTML body properly and was looking for an alternative when I found Peter Huber's article "POP3 Email Client (.NET 2.0)". I discovered that with a little modification, his
Pop3MimeClient classes will also read EML files. I contacted him and told him that I would be changing some of his code and updating my article and he was obligated to that idea.
Pop3MimeClient was also renamed to
MimeReader since its purpose does not necessarily have anything to do with Pop3.
My intent was to have an SMTP service I could send messages to that would process those messages. The recipient email name was an identifier but it was difficult to predict what it might be. The host name was the server. Sending to email@example.com would create an EML file in the SMTP services Drop area (for Microsoft SMTP, usually c:\inetpub\mailroot\drop). I could then pull off all the mail recipients (To, CC and BCC) and process the body message as needed. To use Pop3, I would have had to log in to each Pop3 account or use a Pop3 catch-all account. I was willing to go this route until I found out that Microsoft was going to remove the Pop3 Server from all Microsoft Server platforms after Windows Server 2003. It also seemed a little silly to use Pop3 if I could just find a way to read the EML files directly. Then I found Peter's article.
Using the Code
Let's keep this simple. I'm sure you all know how to get file paths from a directory so I won't bother showing that. It's just a simple matter of creating a
MimeReader and using it to get the an
RxMailMessage object by specifying the EML path.
MimeReader mime = new MimeReader();
RxMailMessage mm = mime.GetEmail(sEmlPath);
I had to look through the
MailMessage AlternateViews to find the message body in some cases:
private string GetPlainText(RxMailMessage mm)
if (!mm.IsBodyHtml && !string.IsNullOrEmpty(mm.Body))
string sText = string.Empty;
foreach (AlternateView av in mm.AlternateViews)
if (string.Compare(av.ContentType.MediaType, "text/plain", true) == 0)
if (string.Compare(av.ContentType.MediaType, "text/html", true) == 0)
sText = StreamToString(av.ContentStream);
if (sText == string.Empty && mm.IsBodyHtml && !string.IsNullOrEmpty(mm.Body))
sText = mm.Body;
if (sText == string.Empty)
private static string StreamToString(Stream stream)
string sText = string.Empty;
using (StreamReader sr = new StreamReader(stream))
sText = sr.ReadToEnd();
stream.Seek(0, SeekOrigin.Begin); stream.Close();
Points of Interest
Some parts of Peter's original
MimeReader) just didn't seem to work for me, in particular, the setting of content-disposition header field in
ProcessHeaderField and the
This supercedes the original Easily retrieve email information from .EML files article I had written.