Click here to Skip to main content
Click here to Skip to main content

POP3 Client

By , 12 May 2008
 
ComcastTrayIcon

Introduction

I was faced with a problem recently. I was trying to find a way to get a notification, similar to Outlook, when I get a new message in my Comcast Inbox. There was no software available to do this. As a result, I started a project that would enable me to do so. Slowly but surely, the project has grown to include the following features:

  • Connect to POP3 server (defaults to Comcast)
  • Get total number of messages from the server
  • Get actual message text from the server
  • Include tray notification icon

The project provided has several key classes. The main one is EmailClient. It connects to the server using TCPClient class. All communication occurs using basic .NET classes: NetworkStream and StreamReader. To login, the client is sending basic POP3 commands, including USER and PASS(word). Here is method used to connect and login:

Private _stream As NetworkStream
Private _reader As StreamReader
Private _server As String
Private _user As String
Private _password As String
Private _tcpClient As TcpClient

Private Sub ConnectToServer()
    Try
        _tcpClient.Connect(_server, Port)
        _stream = _tcpClient.GetStream()
        _reader = New StreamReader(_stream)
        _isConnected = True
    Catch ex As Exception
        _isConnected = False
    End Try
End Sub

Private Sub Login()
    _isLoggedIn = False
    If _isConnected Then
        ' send user ID
        Dim data As String = "USER " + _user.Trim + Environment.NewLine
        WriteToServer(data)

        'discard response
        If ReadFromServer(1).Substring(0, GoodResponse.Length) = GoodResponse Then
            ' send password
            data = "PASS " & _password & Environment.NewLine
            WriteToServer(data)
            If ReadFromServer(1).Substring(0, GoodResponse.Length) = GoodResponse Then
                _isLoggedIn = True
            End If
        End If
    End If
End Sub

Additional tray icon functionality is provided via the NotifyIcon class. This class when dropped onto the form provides an easy to use model to get tray icon notifications. For example, this is how we can maximize the form using a double-click event:

Private Sub EmailNotifyIcon_DoubleClick(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles EmailNotifyIcon.DoubleClick
    Me.Show()
    Me.WindowState = FormWindowState.Normal
    EmailTimer.Enabled = True
End Sub

To use the client, create an instance and pass in credentials:

Using email As New EmailClient(Me.txtServer.Text.Trim, _
    Me.txtUser.Text.Trim, Me.txtPassword.Text.Trim)
    If email.IsConnected Then
        If email.IsLoggedIn Then
            messages = email.TotalMessages()
            _messages = email.GetMessageList()
        Else
            Me.EmailNotifyIcon.Text = "Email - Invalid login/server."
            EmailNotifyIcon.ShowBalloonTip(10000, "Email", _
                "Invalid server/login", ToolTipIcon.Error)
            messages = -2
        End If
        btnPreview.Enabled = (messages > 0)
    Else
        Me.EmailNotifyIcon.Text = "Email - Invalid login/server."
        EmailNotifyIcon.ShowBalloonTip(10000, "Email", _
                "Invalid server/login", ToolTipIcon.Error)
        messages = -2
    End If
End Using

In addition to that, browser control was used to provide the preview functionality. To achieve that, email plain text is parsed and HTML is extracted out. The HTML is then output to a file in the executable folder. Finally, the browser control is created, sized to the preview form size and its URL is set to email file:

Dim url As Uri = New System.Uri(oneMessage.CreateHTMLFile())

    Public Function CreateHTMLFile() As String
        Dim folder As String = My.Application.Info.DirectoryPath
        If Not folder.EndsWith(IO.Path.DirectorySeparatorChar) Then
            folder = folder & IO.Path.DirectorySeparatorChar
        End If
        Dim fileName As String = folder & "email_" & _messageNumber.ToString & ".html"
        IO.File.WriteAllText(fileName, _html)
        Return fileName
    End Function

Please download and review the project for more details.

History

  • 12th May, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sergey Barskiy
Software Developer (Senior) Magenic
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralAttachmentsmemberSmithers92921 May '11 - 13:59 
Is it possible to download attachments?
 

Any help would be great.
My Mail: space12@gmx.de
 
Thanks
Sarah
GeneralRe: AttachmentsmemberSergey Barskiy22 May '11 - 2:40 
Unfortunately, no. I could not find any facility to do so,
Sergey Barskiy

QuestionHow to Read folder lik "junk" or any customized folder on mailserver?memberjymitra19 Jul '10 - 21:45 
HI ,,
What if i want to access email from customized folder it may b any folder lik person name or junk ?
please help me about this topic .i hv done R&D lot but no result ..please help me ..
 
email me @ jymitra03@gmail.com
GeneralTo get code in to C#memberNitinMakwana23 Feb '10 - 2:58 
Hello Sir,
The Code Provided By U is such a nice code & its working nicely but we need the code into C#.Net so if you had converted this code into c# then Please send the link to me.....
 

Also we need to get attachments from the Emails so if u had implemented that code then also send it to me.....
 

 
Thanks.....
 

My ID:=> nicky_mk007@yahoo.co.in
AnswerRe: To get code in to C#mvpthatraja28 Jan '12 - 6:02 
NitinMakwana wrote:
but we need the code into C#.Net

Check this blog post .NET Code Conversion[^]
thatraja

FREE Code Conversion VB6 ASP VB.NET C# ASP.NET C++ JAVA PHP DELPHI | Nobody remains a virgin, Life screws everyone Sigh | :sigh:

GeneralSslmemberblacer27 May '09 - 23:19 
I made some changes to your code to access a mailbox by ssl. Might help someone ..
 
Private _stream As SslStream
    Public Function Certify( _
    ByVal sender As Object, _
    ByVal certificate As Security.Cryptography.X509Certificates.X509Certificate, _
    ByVal chain As Security.Cryptography.X509Certificates.X509Chain, _
    ByVal sslPolicyErrors As SslPolicyErrors _
    ) As Boolean
        If sslPolicyErrors = sslPolicyErrors.None Then
            Return True
        End If
        Return False
    End Function
 
    ''' <summary>
    ''' Establish connection to the server
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub ConnectToServer()
        Try
            _tcpClient.Connect(_server, Port)
            _stream = New SslStream(_tcpClient.GetStream(), False, New RemoteCertificateValidationCallback(AddressOf Certify), Nothing)
            _stream.AuthenticateAsClient(_server)
 
            _reader = New StreamReader(_stream)
            _isConnected = True
        Catch ex As Exception
            _isConnected = False
        End Try
    End Sub

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 12 May 2008
Article Copyright 2008 by Sergey Barskiy
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid