Introduction
This article discusses how to successfully receive a response from a pop3 mail server (i.e. Gmail) using your programming skills, not just a third party class, using .NET Framework 4 and VB2010 (TcpClient
) class.
This is more like a full E-mail client project but still in the beginning, so this will be updated many times .
Background
Since Microsoft did not release a POP3 class that directly enables programmers to use in order to interact with mail servers (i.e., Gmail) to download emails of their own or provide applications for clients that helps in receiving email from email servers, i thought it would be OK to start my own project using the VB2010 along with .Net framework technology.
Also i want to say that most of the vb.net application i downloaded and tested did not really work for me for many reasons such as they are old posts or using the wrong settings or written in different languages like C#, C++ or java, so i really wanted to create a VB.Net example using only VB.Net tools.
Using the code
I'm using : WinXPSp3, VB2010 Pro. and .NET Framework 4
No special functions or anything just a very simple way to receive response from Gmail pop server.
I have only one form in my VB2010 project called [Form1] and here is a picture for it:
So all you need to do is create a new project and save it to your hard desk.
The code goes like this :
Imports System.IO
Imports System.Net.Sockets
Imports System.Text
Imports System.Net.Security
Imports System.Net
Class Form1
Dim PopHost As String
Dim UserName As String
Dim Password As String
Dim PortNm As Integer
Dim POP3 As New TcpClient
Dim Read_Stream As StreamReader
Dim NetworkS_tream As NetworkStream
Dim m_sslStream As SslStream
Dim server_Command, Sent_Val As String
Dim m_buffer() As Byte
Private Sub CmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdDownload.Click
PopHost = TxtHost.Text
UserName = TxtUsrNm.Text
Password = TxtPass.Text
PortNm = TxtPort.Text
Cursor = Cursors.WaitCursor
POP3.Connect(PopHost, Integer.Parse(PortNm))
Login
Cursor = Cursors.Default
End Sub
Sub Login()
NetworkS_tream = POP3.GetStream()
m_sslStream = New SslStream(NetworkS_tream)
m_sslStream.AuthenticateAsClient(PopHost)
Read_Stream = New StreamReader(m_sslStream)
ListBox1.Items.Add(Read_Stream.ReadLine())
server_Command = "USER " + UserName + vbCrLf
m_buffer = System.Text.Encoding.ASCII.GetBytes(server_Command.ToCharArray())
m_sslStream.Write(m_buffer, 0, m_buffer.Length)
ListBox1.Items.Add(Read_Stream.ReadLine())
server_Command = "PASS " + Password + vbCrLf
m_buffer = System.Text.Encoding.ASCII.GetBytes(server_Command.ToCharArray())
m_sslStream.Write(m_buffer, 0, m_buffer.Length)
ListBox1.Items.Add(Read_Stream.ReadLine())
server_Command = "STAT " + vbCrLf
m_buffer = System.Text.Encoding.ASCII.GetBytes(server_Command.ToCharArray())
m_sslStream.Write(m_buffer, 0, m_buffer.Length)
ListBox1.Items.Add(Read_Stream.ReadLine())
End Sub
End Class
Update (1) 17, Aug, 2012 : Retrieve the Number of E-mails from Inbox
Code for update (1) :
Dim server_Stat(2) As String
server_Stat = StatResp.Split(" ")
MsgCount.Text = server_Stat(1)
Link for update NO. 1 - Here
This update discusses :
- The difference between Get Emails from Gmail.com and Hotmail.com
- Setting up your Gmail.com account to receive the new unread e-mails or the total number of E-mails generally.
- Hotmail.com server won't show the difference between the unread E-mails or the total number of E-mails.
- Receiving the number of E-mails in a TextBox control [MsgCount].
Photo for update (1) :
Update (2) 18, Aug, 2012 : Download E-mails from POP3 Server into TextBox
Code for update (2) : This will be a replace of the main code above .
Imports System.IO
Imports System.Net.Sockets
Imports System.Text
Imports System.Net.Security
Imports System.Net
Class Form1
Dim PopHost As String
Dim UserName As String
Dim Password As String
Dim PortNm As Integer
Dim POP3 As New TcpClient
Dim Read_Stream As StreamReader
Dim NetworkS_tream As NetworkStream
Dim m_sslStream As SslStream
Dim server_Command As String
Dim ret_Val As Integer
Dim Response As String
Dim Parts() As String
Dim m_buffer() As Byte
Dim StatResp As String
Dim server_Stat(2) As String
Private Sub CmdDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdDownload.Click
If POP3.Connected = True Then
CloseServer()
POP3 = New TcpClient(PopHost, Integer.Parse(TxtPort.Text))
ret_Val = 0
Exit Sub
Else
PopHost = TxtHost.Text
UserName = TxtUsrNm.Text
Password = TxtPass.Text
PortNm = TxtPort.Text
Cursor = Cursors.WaitCursor
POP3 = New TcpClient(PopHost, Integer.Parse(TxtPort.Text))
NetworkS_tream = POP3.GetStream m_sslStream = New SslStream(NetworkS_tream) m_sslStream.AuthenticateAsClient(PopHost) Read_Stream = New StreamReader(m_sslStream) StatResp = Read_Stream.ReadLine()
ListBox1.Items.Clear()
StatResp = Login(m_sslStream, "USER " & UserName) & vbCrLf
ListBox1.Items.Add(StatResp)
StatResp = Login(m_sslStream, "PASS " & Password) & vbCrLf
ListBox1.Items.Add(StatResp)
StatResp = Login(m_sslStream, "STAT ") & vbCrLf
ListBox1.Items.Add(StatResp)
server_Stat = StatResp.Split(" ")
MsgCount.Text = server_Stat(1)
ret_Val = 1
End If
Cursor = Cursors.Default
CmdClose.Enabled = True
CmdDownload.Enabled = False
End Sub
Sub CloseServer()
StatResp = Login(m_sslStream, "QUIT ") & vbCrLf
ListBox1.Items.Add(StatResp)
ListBox2.Items.Clear()
TextBox1.Text = String.Empty
POP3.Close()
ret_Val = 0
End Sub
Function Login(ByVal SslStrem As SslStream, ByVal Server_Command As String) As String
Dim Read_Stream2 = New StreamReader(SslStrem)
Server_Command = Server_Command + vbCrLf
m_buffer = System.Text.Encoding.ASCII.GetBytes(Server_Command.ToCharArray())
m_sslStream.Write(m_buffer, 0, m_buffer.Length)
Dim Server_Reponse As String
Server_Reponse = Read_Stream2.ReadLine()
Return Server_Reponse
End Function
Private Sub CmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CmdClose.Click
CloseServer()
CmdClose.Enabled = False
CmdDownload.Enabled = True
ret_Val = 0
End Sub
Sub getMesgs(ByVal Num_Emails As Integer)
Cursor = Cursors.WaitCursor
Dim List_Resp As String
Dim I As Integer
For I = 1 To Num_Emails
List_Resp = Login(m_sslStream, "LIST " & I.ToString)
ListBox2.Items.Add(List_Resp)
Next I
Cursor = Cursors.Default
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ret_Val = 0 Then
ListBox2.Items.Add("You are not connected, please connect")
Exit Sub
End If
ListBox2.Items.Clear()
getMesgs(Integer.Parse(server_Stat(1)))
End Sub
Sub GetEmails(ByVal Server_Command As String)
Dim m_buffer() As Byte = System.Text.Encoding.ASCII.GetBytes(Server_Command.ToCharArray())
Dim stream_Reader As StreamReader
Dim TxtLine As String = ""
Try
m_sslStream.Write(m_buffer, 0, m_buffer.Length)
stream_Reader = New StreamReader(m_sslStream)
Do While stream_Reader.Peek() <> -1
TxtLine += stream_Reader.ReadLine() & vbNewLine
Loop
TextBox1.Text = TxtLine
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub ListBox2_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox2.DoubleClick
Dim Index_Num As String
Dim StrRetr As String
TextBox1.Text = ""
Try
Index_Num = (ListBox2.SelectedIndex + 1).ToString
StrRetr = ("RETR " + Index_Num + vbCrLf)
GetEmails(StrRetr)
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Application.Exit()
End Sub
End Class
Link for update NO. 2 - Here
This update discusses :
- How to get a list of all your E-mails from a POP3 server (i.e. Gmail.com)
- Download and read your E-mails as a text format.
- Dressing up your application to be more user-friendly.
- Successfully disconnects from the server and re-login back without any errors.
Photo for update (2) :
Final Update : Jan-2013 Fixing issues and source code download.
This update is about displaying the E-mail to read it : I noticed that sometimes the the E-mail won't arrive in full, even with a double click the whole stream package doesn't fully transfered to the TextBox and you get just a part of it, also most of the times (and it depends on the E-mail Server) the request doesn't execute the way it was requested, I.E. if you clicked on E-mail mail message No.1 and then you clicked on Message No.2 you would get the No.1 still. (Download and full description in the Update section below)
Points of Interest
You will notice that after you try this, you will get response from the gmail server, but :
- You need to be familiar with POP commands, you can find reference here .
- If you are using 2-step verification method in your Gmail account, you will need to create an application password to be able to login from outside Google, here is how!
- Also you may want to consider using outlook as a start if you haven't work before with e-mail clients only to make sure that the service is working fine between you and the server .
- If you had any errors trying this code please post it, i already tried this on all of the MS OSs.
Problems to be solved later in further updates
The problem is that in Gmail.com we will retrieve all E-mails from Inbox and all other folders so if you have (22) E-mails in Inbox and (20) in SentBox and (50) in Trash then we will be getting (22+20+50) = 92 E-mails and we won't be able to tell which one is in which Box, but we will come to this later in our project.
Also the E-mails downloaded will be in absolute Text format, so there will be no links or images displayed at the moment, but we will come to this also later.
How does it work now ?!
Before I start let me tell you that :
Logout button is [Enabled=False] from properties panel.
TextBox1 for reading E-mails is [ReadOnly=True] and [MultiLine=True] from properties panel.
Now, it goes like this :
- Ctrl+F5 The application starts up you will find Logout button is disabled so you can not logout before you Login
- You click on Login Button, if the info provided are successful then you will receive 3 lines in Server Response ListBox1 as shown in the Photo above.
- You will then notice that Login Button is disabled and the Logout Button is now enabled.
- If you choosed to click on Logout Button now you will notice that a 4th line is added to the Server Response ListBox1 [+OK Farewell] and it means that you are now disconnected from the POP3 server.
- Clicking on Login Button again will get you back on track and be logged in and also you will find the number of E-mails in the Messages TextBox [MsgCount] .... see update (2) for more information about this number of E-mails .
- Clicking now on Get E-mails List [Button1] will make the application busy retrieving your E-mails into The ListBox2 and you will be able to see the scrollBar shrinking as a sign of retrieving the Messages.
- After the List of messages successfully fills the [ListBox2] you can now DoubleClick on any number of this list to read this E-mail in the TextBox1 as absolute Text format which we will be handling it later to be more user friendly. (Final Update)
- Clicking on Logout [CmdClose] again will disconnect the server and empty all controls except your loggin settings and disable the Logout Button [CmdClose] and enables the Login Button [CmdDownload] again to start over.
History
Link for update NO. 1 - Here
Link for update NO. 2 - Here
Link for Final update NO. 3 - Here