Parse Email Body, Attachment and Convert Email to HTML page in C#

In previous section, I introduced how to parse winmail.dat. In this section, I will introduce how to parse email body and attachment, then convert email to a HTML page and display it using Web browser in C#.

Introduction

After the email was converted to HTML page, you can browse it with web browser. You can get everything in the HTML page such as From, To, Cc, Subject, Date, Attachments and Embedded images.

Note

Remarks: All of examples in this section are based on first section: A simple C# project. To compile and run the following example codes successfully, please click here to learn how to create the test project and add reference to your project.

[C# Example - Convert email to HTML]

The following example codes demonstrate how to use EAGetMail POP3 component to convert email to HTML page.

Note

To get the full sample projects, please refer to Samples section.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using EAGetMail; //add EAGetMail namespace

namespace receiveemail
{
    class Program
    {
        private static void ConvertMailToHtml(string fileName)
        {
            try
            {
                int pos = fileName.LastIndexOf(".");
                string mainName = fileName.Substring(0, pos);
                string htmlName = mainName + ".htm";

                string tempFolder = mainName;
                if (!File.Exists(htmlName))
                {
                    // We haven't generate the html for this email, generate it now.
                    _GenerateHtmlForEmail(htmlName, fileName, tempFolder);
                }

                Console.WriteLine("Please open {0} to browse your email",
                    htmlName);
            }
            catch (Exception ep)
            {
                Console.WriteLine(ep.Message);
            }
        }

        private static string _FormatHtmlTag(string src)
        {
            src = src.Replace(">", ">");
            src = src.Replace("<", "&lt;");
            return src;
        }

        // We generate a html + attachment folder for every email, once the html is create,
        // next time we don't need to parse the email again.
        private static void _GenerateHtmlForEmail(string htmlName, string emlFile,
                            string tempFolder)
        {
            Mail oMail = new Mail("TryIt");
            oMail.Load(emlFile, false);

            if (oMail.IsEncrypted)
            {
                try
                {
                    // This email is encrypted, we decrypt it by user default certificate.
                    oMail = oMail.Decrypt(null);
                }
                catch (Exception ep)
                {
                    Console.WriteLine(ep.Message);
                    oMail.Load(emlFile, false);
                }
            }

            if (oMail.IsSigned)
            {
                try
                {
                    // This email is digital signed.
                    EAGetMail.Certificate cert = oMail.VerifySignature();
                    Console.WriteLine("This email contains a valid digital signature.");
                }
                catch (Exception ep)
                {
                    Console.WriteLine(ep.Message);
                }
            }

            // Decode winmail.dat (TNEF) automatically
            // also convert RTF body to HTML body automatically.
            oMail.DecodeTNEF();

            // Parse html body
            string html = oMail.HtmlBody;
            StringBuilder hdr = new StringBuilder();

            // Parse sender
            hdr.Append("<font face=\"Courier New,Arial\" size=2>");
            hdr.Append("<b>From:</b> " + _FormatHtmlTag(oMail.From.ToString()) + "<br />");

            // Parse to
            MailAddress[] addrs = oMail.To;
            int count = addrs.Length;
            if (count > 0)
            {
                hdr.Append("<b>To:</b> ");
                for (int i = 0; i < count; i++)
                {
                    hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
                    if (i < count - 1)
                    {
                        hdr.Append(";");
                    }
                }
                hdr.Append("<br />");
            }

            // Parse cc
            addrs = oMail.Cc;

            count = addrs.Length;
            if (count > 0)
            {
                hdr.Append("<b>Cc:</b> ");
                for (int i = 0; i < count; i++)
                {
                    hdr.Append(_FormatHtmlTag(addrs[i].ToString()));
                    if (i < count - 1)
                    {
                        hdr.Append(";");
                    }
                }
                hdr.Append("<br />");
            }

            hdr.Append(String.Format("<b>Subject:</b>{0}<br />\r\n",
                _FormatHtmlTag(oMail.Subject)));

            // Parse attachments and save to local folder
            Attachment[] atts = oMail.Attachments;
            count = atts.Length;
            if (count > 0)
            {
                if (!Directory.Exists(tempFolder))
                    Directory.CreateDirectory(tempFolder);

                hdr.Append("<b>Attachments:</b>");
                for (int i = 0; i < count; i++)
                {
                    Attachment att = atts[i];

                    string attname = String.Format("{0}\\{1}", tempFolder, att.Name);
                    att.SaveAs(attname, true);
                    hdr.Append(String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a> ",
                            attname, att.Name));
                    if (att.ContentID.Length > 0)
                    {

                        // Show embedded images.
                        html = html.Replace("cid:" + att.ContentID, attname);
                    }
                    else if (String.Compare(att.ContentType, 0, "image/", 0,
                                "image/".Length, true) == 0)
                    {

                        // show attached images.
                        html = html + String.Format("<hr><img src=\"{0}\">", attname);
                    }
                }
            }

            Regex reg = new Regex("(<meta[^>]*charset[ \t]*=[ \t\"]*)([^<> \r\n\"]*)",
                RegexOptions.Multiline | RegexOptions.IgnoreCase);
            html = reg.Replace(html, "$1utf-8");
            if (!reg.IsMatch(html))
            {
                hdr.Insert(0,
                    "<meta HTTP-EQUIV=\"Content-Type\" Content=\"text-html; charset=utf-8\">");
            }

            // write html to file
            html = hdr.ToString() + "<hr>" + html;
            FileStream fs = new FileStream(htmlName, FileMode.Create,
                FileAccess.Write, FileShare.None);

            byte[] data = System.Text.UTF8Encoding.UTF8.GetBytes(html);
            fs.Write(data, 0, data.Length);
            fs.Close();
            oMail.Clear();
        }

        static void Main(string[] args)
        {
            string curpath = Directory.GetCurrentDirectory();
            string mailbox = String.Format("{0}\\inbox", curpath);

            // If the folder is not existed, create it.
            if (!Directory.Exists(mailbox))
            {
                Directory.CreateDirectory(mailbox);
            }
            // Convert all emails received to html page
            string[] files = Directory.GetFiles(mailbox, "*.eml");
            for (int i = 0; i < files.Length; i++)
            {
                ConvertMailToHtml(files[i]);
            }
        }
    }
}

In EAGetMail installer, there are many samples demonstrate how to use Web browser control to display the email, I suggest that you download it and have a try

pop3, imap4 samples

Next Section

At next section I will introduce how to parse Non-delivery report.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.