A simple POP3 library with SSL support in Visual Basic.NET

by Matthias Broschk March 13, 2006 17:37

Sending emails from your .NET program is an easy task, since the Simple Mail Transfer Protocol (SMTP) is part of the framework. Unfortunately the Post Office Protocol (POP3) is not (yet) implemented in the .NET framework and therefore in order to receive emails it is necessary to buy a ready-to-use component or come up with your own solution.

POP3 is a fairly simple protocol and therefore I decided to write my own “quick and dirty” class library. It implements the most common POP3 commands, which are understood by all POP3 servers:

USER xxx

Sends the username
PASS xxx
Send the password (in plain text)
STAT
Returns the status of the mailbox, that is the number of all emails in the mailbox and its total size (in bytes).
LIST (n)
return the number and size of all emails  (with parameter: of the nth email)
RETR n
Fetches the nth email from the email server
DELE n
Deletes the nth email on the email server (flags it as to be deleted)
NOOP
Sends a “No Operation”-request to the server to keep the connection “alive”
RSET
Supersedes/removes any previous DELE commands
QUIT
Ends the current POP3 session and performs all DELE commands

Each statement that is sent to the server consists of a command, zero or more parameters and a closing carriage return/line feed (CRLF or in VB.NET vbCrLf). Each single line response starts either with “+OK” or “-ERR” and also ends with a closing CRLF. All commands except “RETR” result in a single line response. “RETR” results in a single line response and the email split over several CRLF separated lines and ends with a single “.” line.

These facts allow a quite generic implementation, as the following code snippets of helper functions demonstrate.

Private Function SendCommand (ByVal Action As POP3Actions, 
Optional ByVal Parameter1 As String = "", Optional ByVal Parameter2 As String = "") 
As POP3ServerResponse
   
	Dim CommandText As String = [Enum].GetName(GetType(POP3Actions), Action) 
								& IIf(Parameter1 <> "", " " & Parameter1, "") 
								& IIf(Parameter2 <> "", " " & Parameter2, "") & vbCrLf
    Me._CurrentAction = Action

    Me.SendText(CommandText)

    Return Me.GetServerResponse()
End Function
Private Function GetServerResponse() As POP3ServerResponse
    Dim response As New POP3ServerResponse

    response.Text = Me.ReadLine

    If Not response.IsOK Then
        Me.ErrorHandler.HandleError(Me._CurrentAction, response.Text)

        Me.CloseSocket()
    End If

    Me._CurrentAction = POP3Actions._None

    Return response
End Function

With these helper functions it is for instance possible to write the login procedure with a few simple lines.

Public Function Connect() As Boolean
    Me._Socket = New TcpClient

    If Not Me.ConnectSocket() Then Return False

    If Not Me.GetServerResponse().IsOK Then Return False

    If Not Me.SendCommand(POP3Actions.USER, Me.User).IsOK Then Return False

    If Not Me.SendCommand(POP3Actions.PASS, Me.Password).IsOK Then Return False

    Return True
End Function

One of the problems with POP3 is that the password is sent to the server in plain text . The solution for this is SSL, which can be used in combination with POP3. Many email providers provide a SSL-secured POP3 access over port 995 (instead of standard port 110). GoogleMail for example requires POP3 over SSL at all times. The following function shows how a SSL connection can be created.

Private ReadOnly Property Stream() As Stream
    Get
        If _Stream Is Nothing Then

            If Me.UseSSL Then
                Dim sslstream As New SslStream(_Socket.GetStream(), False)
                sslstream.AuthenticateAsClient(Me.Server)
                _Stream = sslstream
            Else
                _Stream = _Socket.GetStream()
            End If

        End If

        Return _Stream
    End Get
End Property

In the solution you will find a demo included, which will help you test the class library.

Screenshot

This is a simple, but powerful POP3 library for .NET. Unfortunately it can only download emails as a whole raw text, not parse them. So if you want to extract common fields such as sender, recipient or content, I would recommend one of the following mime parsers: 1, 2, 3.

The full source code can be found here.

Tags: , , , ,

Visual Basic.NET

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen | Modified by Mooglegiant

About the author

Matthias Broschk from Hamburg (Germany) wrote his first goto statements in QuickBasic at the age of fifteen, switched to Visual Studio (i.e. Visual Basic / Visual C++) at version 5.0 and has been an addict of .NET since its early beginnings. There have been many other languages and frameworks (Java, PHP, ... ), but none about which he has been as enthusiastic as .NET. These days you can find more information in blogs rather than anywhere else. Therefore he has decided to share his experiences and start yet another .NET blog.