Parse Email in VB.NET

In previous section, I introduced how to download email with background service. In this section, I will introduce how to parse email in VB.NET.

Introduction

After you received the emails to the local folder, we can use the following code to parse the email now. The following code demonstrates how to parse from, to, cc, subject, body text, attachments of all emails file received by previous sample.

Note

Remarks: All of examples in this section are based on first section: A simple VB.NET 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.

[VB.NET Example - Parse email]

The following example codes demonstrate how to use EAGetMail POP3 component to parse email sender, to, cc, subject, body text and attachments.

Note

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

Imports System.Globalization
Imports System.Text
Imports System.IO
Imports EAGetMail 'imports EAGetMail namespace

Module Module1
    Private Sub ParseEmail(ByVal emlFile As String)
        Dim oMail As New Mail("TryIt")
        oMail.Load(emlFile, False)

        ' Parse Mail From/Sender
        Console.WriteLine("From: {0}", oMail.From.ToString())

        ' Parse Mail To/Recipient
        Dim addrs As MailAddress() = oMail.[To]
        For i As Integer = 0 To addrs.Length - 1
            Console.WriteLine("To: {0}", addrs(i).ToString())
        Next

        ' Parse Mail CC
        addrs = oMail.Cc
        For i As Integer = 0 To addrs.Length - 1
            Console.WriteLine("To: {0}", addrs(i).ToString())
        Next

        ' Parse Mail Subject
        Console.WriteLine("Subject: {0}", oMail.Subject)

        ' Parse Mail Text/Plain body
        Console.WriteLine("TextBody: {0}", oMail.TextBody)

        ' Parse Mail Html Body
        Console.WriteLine("HtmlBody: {0}", oMail.HtmlBody)

        ' Parse Attachments
        Dim atts As Attachment() = oMail.Attachments
        For i As Integer = 0 To atts.Length - 1
            Console.WriteLine("Attachment: {0}", atts(i).Name)
        Next
    End Sub

    Sub Main()
        Try
            ParseEmail("c:\my folder\test.eml")
        Catch ex As Exception
            Console.WriteLine(ex.Message)
        End Try

    End Sub
End Module

TextBody and HtmlBody

Not every email has both text/plain body text and html body text. However, Mail object provides both TextBody and HtmlBody properties smartly. If the email has only text/plain body, then Mail object converts the text/plain body to html body automatically; if the email has only html body, then Mail object converts the html body to text/plain body automatically.

Next Section

At next section I will introduce how to verify digital signature and decrypt email.

Appendix

Comments

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