VB.NET - Convert Email to HTML

The following vb.net codes demonstrate how to convert email to a HTML page and display it using Web browser Control.

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.

Installation

Before you can use the following sample codes, you should download the EAGetMail Installer and install it on your machine at first. Full sample projects are included in this installer.

Install from NuGet

You can also install the run-time assembly by NuGet. Run the following command in the NuGet Package Manager Console:

Install-Package EAGetMail

Note

If you install it by NuGet, no sample projects are installed, only .NET assembly is installed.

Add Reference

To use EAGetMail POP3 & IMAP Component in your project, the first step is “Add reference of EAGetMail to your project”. Please create or open your project with Visual Studio, then go to menu -> Project -> Add Reference -> .NET -> Browse..., and select EAGetMail{version}.dll from installation path, click Open-> OK, the reference will be added to the project, you can start to use it to retrieve email and parse email in your project.

add reference in c#/vb.net/managed c++/cli

.NET Assembly

Because EAGetMail has separate builds for .Net Framework, please refer to the following table and choose the correct dll.

Separate builds of run-time assembly for .Net Framework 1.1, 2.0, 3.5, 4.0, 4.5 and .Net Compact Framework 2.0, 3.5.

File .NET Framework Version
EAGetMail.dll Built with .NET Framework 1.1
It requires .NET Framework 1.1, 2.0, 3.5 or later version.
EAGetMail20.dll Built with .NET Framework 2.0
It requires .NET Framework 2.0, 3.5 or later version.
EAGetMail35.dll Built with .NET Framework 3.5
It requires .NET Framework 3.5 or later version.
EAGetMail40.dll Built with .NET Framework 4.0
It requires .NET Framework 4.0 or later version.
EAGetMail45.dll Built with .NET Framework 4.5
It requires .NET Framework 4.5 or later version.
EAGetMailCF20.dll Built with .NET Compact Framework 2.0
It requires .NET Compact Framework 2.0, 3.5 or later version.
EAGetMailCF35.dll Built with .NET Compact Framework 3.5
It requires .NET Compact Framework 3.5 or later version.

VB.NET - Parse and Convert Email to HTML - Example

The following example codes demonstrate converting email to HTML page. In order to run it correctly, please change email server, user, password, folder, file name value to yours.

Note

To get full sample projects, please download and install EAGetMail on your machine.

Imports System.Collections
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.IO

' Imports EAGetMail namespace
Imports EAGetMail

Module Module1
    Private Sub ConvertMailToHtml(ByVal fileName As String)
        Try
            Dim pos As Integer = fileName.LastIndexOf(".")
            Dim mainName As String = fileName.Substring(0, pos)
            Dim htmlName As String = mainName & ".htm"

            Dim tempFolder As String = mainName
            If Not File.Exists(htmlName) Then

                ' We haven't generate the html for this email, generate it now.
                _GenerateHtmlForEmail(htmlName, fileName, tempFolder)
            End If

            Console.WriteLine("Please open {0} to browse your email", htmlName)
        Catch ep As Exception
            Console.WriteLine(ep.Message)
        End Try
    End Sub

    Private Function _FormatHtmlTag(ByVal src As String) As String
        src = src.Replace(">", ">")
        src = src.Replace("<", "&lt;")
        Return src
    End Function

    ' 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 Sub _GenerateHtmlForEmail(ByVal htmlName As String, _
            ByVal emlFile As String, ByVal tempFolder As String)
        Dim oMail As New Mail("TryIt")
        oMail.Load(emlFile, False)

        If oMail.IsEncrypted Then
            Try

                ' This email is encrypted, we decrypt it by user default certificate.
                oMail = oMail.Decrypt(Nothing)
            Catch ep As Exception
                Console.WriteLine(ep.Message)
                oMail.Load(emlFile, False)
            End Try
        End If

        If oMail.IsSigned Then
            Try
                ' This email is digital signed.
                Dim cert As EAGetMail.Certificate = oMail.VerifySignature()
                Console.WriteLine("This email contains a valid digital signature.")
            Catch ep As Exception
                Console.WriteLine(ep.Message)
            End Try
        End If

        ' Parse html body
        Dim html As String = oMail.HtmlBody
        Dim hdr As 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
        Dim addrs As MailAddress() = oMail.[To]
        Dim count As Integer = addrs.Length
        If count > 0 Then
            hdr.Append("<b>To:</b> ")
            For i As Integer = 0 To count - 1
                hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
                If i < count - 1 Then
                    hdr.Append(";")
                End If
            Next
            hdr.Append("<br>")
        End If

        ' Parse cc
        addrs = oMail.Cc

        count = addrs.Length
        If count > 0 Then
            hdr.Append("<b>Cc:</b> ")
            For i As Integer = 0 To count - 1
                hdr.Append(_FormatHtmlTag(addrs(i).ToString()))
                If i < count - 1 Then
                    hdr.Append(";")
                End If
            Next
            hdr.Append("<br>")
        End If

        hdr.Append([String].Format("<b>Subject:</b>{0}<br>" & vbCr & vbLf, _
            _FormatHtmlTag(oMail.Subject)))

        ' Parse attachments and save to local folder
        Dim atts As Attachment() = oMail.Attachments
        count = atts.Length
        If count > 0 Then
            If Not Directory.Exists(tempFolder) Then
                Directory.CreateDirectory(tempFolder)
            End If

            hdr.Append("<b>Attachments:</b>")
            For i As Integer = 0 To count - 1
                Dim att As Attachment = atts(i)

                ' This attachment is in OUTLOOK RTF format, decode it here.
                If String.Compare(att.Name, "winmail.dat") = 0 Then
                    Dim tatts As Attachment() = Nothing
                    Try
                        tatts = Mail.ParseTNEF(att.Content, True)
                    Catch ep As Exception
                        Console.WriteLine(ep.Message)
                    End Try

                    Dim y As Integer = tatts.Length
                    For x As Integer = 0 To y - 1
                        Dim tatt As Attachment = tatts(x)
                        Dim tattname As String = String.Format("{0}\{1}", _
                                tempFolder, tatt.Name)
                        tatt.SaveAs(tattname, True)
                        hdr.Append(_
                            String.Format("<a href=""{0}"" target=""_blank"">{1}</a> ", _
                            tattname, tatt.Name))
                    Next
                    Continue For
                End If

                Dim attname As String = 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 Then

                    ' Show embedded images.
                    html = html.Replace("cid:" + att.ContentID, attname)
                ElseIf [String].Compare(att.ContentType, 0, "image/", 0, _
                        "image/".Length, True) = 0 Then

                    ' Show attached images.
                    html = html & String.Format("<hr><img src=""{0}"">", attname)
                End If
            Next
        End If

        Dim reg As New Regex("(<meta[^>]*charset[ " & vbTab & "]*=[ " _
            & vbTab & """]*)([^<> " & vbCr & vbLf & """]*)", _
            RegexOptions.Multiline Or RegexOptions.IgnoreCase)
        html = reg.Replace(html, "$1utf-8")
        If Not reg.IsMatch(html) Then
            hdr.Insert(0, _
            "<meta HTTP-EQUIV=""Content-Type"" Content=""text-html; charset=utf-8"">")
        End If

        ' Write html to file
        html = hdr.ToString() & "<hr>" & html
        Dim fs As New FileStream(htmlName, FileMode.Create, FileAccess.Write, FileShare.None)

        Dim data As Byte() = System.Text.UTF8Encoding.UTF8.GetBytes(html)
        fs.Write(data, 0, data.Length)
        fs.Close()
        oMail.Clear()
    End Sub

    Sub Main()

        ConvertMailToHtml("c:\my folder\test.eml")

    End Sub
End Module

Appendix

Comments

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