Receive Email Walkthrough: for C# and VB NET Students
In the previous lesson, we logged on to the pop3 server. In this lesson, we'll write code to check if there are any emails waiting, by using the STAT command. This will get you how many emails are on the server, and the total size (in octets). Let's see how it works.
Add the following function/method to your code:
Private Function GetMailStats( ) As String
private string GetMailStats()
To issue the STAT command to the POP3 server, we only need to use our PopCommand function. Again, though, we need our NetworkStream object as the first parameter. Add this line to your new function/method:
Dim statsResponse As String = PopCommand( networkStream, "STAT" )
string statsResponse = PopCommand(networkStream, "STAT");
The final line for this function is the return value:
Your coding window should look like this in VB Net:
And this in C#:
Add a call to this function from your Connect button, just under your USER and PASS lines:
Dim serverStats As String = GetMailStats( )
string serverStats = GetMailStats();
Place the string in the textbox, just so that you can see what the response is:
txtServerResponse.Text += serverStats & vbCrLf
txtServerResponse.Text += serverStats + "\r\n";
The Try Catch block in your BtnConnect code should then look like ours:
Before running your programme and trying out the new code, send yourself an email or two, just so that you have something waiting. When you click your Connect button, your Server Response text box should show you the STATs about your emails:
After the +OK response we have the number of emails (11) followed by the number of octets (36304156). Note the spaces in the line of text, one after +OK and one after the 11. We need to parse this line to get how many emails there are. We need the number of emails for the LIST command.
To get at the number of emails, add the following lines to your BtnConnect code, just under the two lines you've just added:
Dim aryStats(2) As String
aryStats = serverStats.Split(" ")
txtServerResponse.Text += "number of emails: " & aryStats(1) & vbCrLf
string aryStats = new string;
aryStats = serverStats.Split(' ');
txtServerResponse.Text += "Number of emails: " + aryStats + "\r\n";
The first line sets up a String array with three positions in it. The second line splits the server stats based on where the space is. This will get you three values. The first value is the +OK response, while the next two are the number of emails and the octet size. The third line in the code above displays the number of emails on a line of its own in the text box.
Now that you have how many emails there are on the server, you need to get a list of all of them. We'll do that in the next lesson below.