Retrieve Email with Event Handler in VB.NET

In previous section, I introduced how to retrieve email from Hotmail/MSN Live account. In this section, I will introduce how to retrieve email with event handler in VB.NET.

Introduction

After Connect method, GetMail method or other methods are invoked, if you want to know the progress of the email receiving, you should use Event Handler. The following sample codes demonstrate how to use Event Handler to monitor the progress of email receiving.

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 - Retrieve email with event handler]

The following example codes demonstrate how to use EAGetMail POP3 component to retrieve email with event handler. In order to run it correctly, please change email server, user, password, folder, file name values.

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 OnConnected(ByVal sender As Object, ByRef cancel As Boolean)
        Console.WriteLine("Connected")
    End Sub

    Private Sub OnQuit(ByVal sender As Object, ByRef cancel As Boolean)
        Console.WriteLine("Quit")
    End Sub

    Private Sub OnReceivingDataStream(ByVal sender As Object, ByVal info As MailInfo, _
        ByVal received As Integer, ByVal total As Integer, ByRef cancel As Boolean)
        Console.WriteLine(String.Format("Receiving {0}, {1}/{2}...", info.Index, _
        received, total))
    End Sub

    Private Sub OnIdle(ByVal sender As Object, ByRef cancel As Boolean)

    End Sub

    Private Sub OnAuthorized(ByVal sender As Object, ByRef cancel As Boolean)
        Console.WriteLine("Authorized")
    End Sub

    Private Sub OnSecuring(ByVal sender As Object, ByRef cancel As Boolean)
        Console.WriteLine("Securing ...")
    End Sub

    Function _generateFileName(ByVal sequence As Integer) As String
        Dim currentDateTime As DateTime = DateTime.Now
        Return String.Format("{0}-{1:000}-{2:000}.eml",
                            currentDateTime.ToString("yyyyMMddHHmmss", New CultureInfo("en-US")),
                            currentDateTime.Millisecond,
                            sequence)
    End Function

    Sub Main()

        Try
            ' Create a folder named "inbox" under current directory
            ' to save the email retrieved.
            Dim localInbox As String = String.Format("{0}\inbox", Directory.GetCurrentDirectory())

            ' If the folder is not existed, create it.
            If Not Directory.Exists(localInbox) Then
                Directory.CreateDirectory(localInbox)
            End If

            Dim oServer As New MailServer("pop3.emailarchitect.net",
                        "test@emailarchitect.net",
                        "testpassword",
                        ServerProtocol.Pop3)

            ' Enable SSL/TLS connection, most modern email server require SSL/TLS connection by default.
            oServer.SSLConnection = True
            oServer.Port = 995

            ' If your server doesn't support SSL/TLS connection, please use the following codes
            ' oServer.SSLConnection = False
            ' oServer.Port = 110

            Console.WriteLine("Connecting server ...")

            Dim oClient As New MailClient("TryIt")

            ' Catching the following events is not necessary,
            ' just make the application more user friendly.
            ' If you use the object in asp.net/windows service or non-gui application,
            ' You need not to catch the following events.
            ' To learn more detail, please refer to the code in EAGetMail EventHandler
            AddHandler oClient.OnAuthorized, AddressOf OnAuthorized
            AddHandler oClient.OnConnected, AddressOf OnConnected
            AddHandler oClient.OnIdle, AddressOf OnIdle
            AddHandler oClient.OnSecuring, AddressOf OnSecuring
            AddHandler oClient.OnReceivingDataStream, AddressOf OnReceivingDataStream

            oClient.Connect(oServer)

            Dim infos As MailInfo() = oClient.GetMailInfos()
            Console.WriteLine("Total {0} email(s)", infos.Length)

            For i As Integer = 0 To infos.Length - 1
                Dim info As MailInfo = infos(i)
                Console.WriteLine("Index: {0}; Size: {1}; UIDL: {2}",
                        info.Index, info.Size, info.UIDL)

                ' Retrieve email from POP3 server
                Dim oMail As Mail = oClient.GetMail(info)

                Console.WriteLine("From: {0}", oMail.From.ToString())
                Console.WriteLine("Subject: {0}" & vbCr & vbLf, oMail.Subject)

                ' Generate an unqiue email file name based on date time.
                Dim fileName As String = _generateFileName(i + 1)
                Dim fullPath As String = String.Format("{0}\{1}", localInbox, fileName)

                ' Save email to local disk
                oMail.SaveAs(fullPath, True)

                ' Mark email as deleted from POP3 server.
                oClient.Delete(info)

            Next

            ' Quit and expunge emails marked as deleted from POP3 server.
            oClient.Quit()
            Console.WriteLine("Completed!")

        Catch ep As Exception
            Console.WriteLine(ep.Message)
        End Try

    End Sub
End Module

Next Section

At next section I will introduce how to use UIDL function to mark the email has been downloaded.

Appendix

Comments

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