Receive Email Walkthrough: for C# and VB NET Students
In the previous lesson, you queried the server for how many emails are on the server and the total size in octets. What we need to do now is get a list of each individual email. You use the LIST command for this. What you get back from LIST is something like this:
This means email 1 has a size of 5680 octets, email 2 has a size of 6632 octets, and so on.
What we'll do is to loop round all the messages we have waiting and put each one in the ListBox at the top of our form. You'll then see the email number and its size in octets. Selecting a message number in the list will enable us to grab the message contents from the server.
Add the following Sub to your code in VB Net:
Private Sub GetMailList( numOfEmails As Integer )
Or this void method in C#:
private void GetMailList(int numOfEmails)
In between the round brackets of the Sub or method, we have the number of emails as an argument. We'll pass in the figure we got from the server.
The code for your new Sub in VB Net is this:
Dim listResponse As String
Dim i As Integer
For i = 1 To numOfEmails
listResponse = PopCommand( networkStream, "LIST
" & i.ToString )
ListBox1.Items.Add( listResponse )
And this, in C#
for (int i = 0; i < numOfEmails; i++)
listResponse = PopCommand(networkStream, "LIST
" + i.ToString());
What we're trying to do here is to loop round issuing the LIST command to the POP3 server. The LIST command works like this:
This will get the server to LIST email number 1. We're then adding the server response to the ListBox at the top of our form. Our loop goes from 1 to the number of emails we have received.
To call the new Sub/method, add this to your BtnConnect code, just under the lines that Splits the serverStats. Right at the end of the Try part, in other words:
If Integer.Parse( aryStats(1) ) > 0 Then
Call GetMailList( Integer.Parse(aryStats(1)) )
if (int.Parse(aryStats) > 0)
GetMailList( int.Parse(aryStats) );
Here, we're just adding an IF statement to check if the value in aryStats(1) is greater than zero. If it's not, it means there's no emails to get. The code for the if statement calls the new Sub/method, passing in the number of emails on the server. You need to convert the value in the array to an integer.
The Try Catch part of your Connect button code should look like this in VB Net:
And this in C#:
And your new GetMailList Sub/method should look like this in VB Net:
And here is the code in C#:
When you run your programme, you should see something like this appear in the ListBox at the top of your code:
After the +OK, the ListBox shows the email number, followed by the size in octets of each email.
Now that we have a list of each individual email, we can write the code for when an item is selected in the Email List. This will enable us to get the email itself and display it in the text box at the bottom of our form. We'll do that in the next lesson.