Microsoft vs. NET development tools have been available for some time, and the new language C # has become increasingly familiar and accepted. C # as an emerging language, I believe it has incomparable advantages over traditional languages. Especially in terms of network applications, developers feel the powerful functions of C. Therefore, this article uses C # To implement a POP3-based email receiving program to show you the powerful functions of C # network programming, we will also introduce the principles of POP3-based email reception.
First, I will introduce you to the basic principles of email reception:
At the beginning, it was the connection between the client and the server. However, before connecting the client to the server, set the port to the default port number 110 of POP3 protocol.
After the client successfully connects to the server, the server returns the following information:
+ OK ......
Character + OK is the return information of POP3 protocol. Unlike the SMTP protocol, its response information is represented by a variety of numbers, with only two: + OK or-err. + OK indicates that the connection is successful, and-err indicates that the connection fails.
Next, enter the user <User Name>
This command tells the server your user name. Note that some servers are case-sensitive.
After the server returns + OK, the client enters the pass <password>
After the server returns + OK, it also returns some mailbox statistics, such as: + OK 1 message (s) [1304 byte (s)]
The formats returned by different servers are not the same, so we can use the STAT command to view the mailbox information. The STAT command responds with two numbers, indicating the number of mails and the size of mails, respectively.
If there is a letter in the mailbox, you can use the RETR command to obtain the body of the email. RETR Command Format:
RETR <email no.>
If the first row of the returned result is + OK, the operation is successful. The body of the email starts from the second line. The last line, like the SMTP protocol, is a separate English ending, indicating the end of the mail.
After storing the emails, use the DELE command to delete the emails in the mailbox. Otherwise, the original emails will be retained on the server. Once there are more emails, your mailbox will pop up. The DELE command format is:
Dele <email no.>
If the deletion is incorrect, run the rset command to restore all deleted emails. The condition is that you have not exited. Once you quit, it will be all bytes. After all, enter the quit command to exit the POP3 server.
Implementation
As mentioned above, I briefly introduced the basic process and principle of POP3 mail reception. The following is a simple mail receiving program based on the above principle. With an understanding of the Basic Principles, programming becomes quite easy. In this program, I mainly use two classes: tcpclient class and networkstream class. Tcpclient class is a very important class that uses C # for network programming. It provides a simple method to connect, send, and receive data through the network, thus greatly simplifying network programming. The networkstream class provides a standard. NET Framework Stream Mechanism for sending and receiving data through network sockets. It supports synchronous and asynchronous access to network data streams and is an important part of network communication. Here I will first show the final running effect of the program, as shown in the figure below:
The procedure is as follows:
Step 1:Open. net, create a project, select "Visual C # Project" in the project type, and select "Windows application" in the template. The project name may be "mailcycler ", click "OK.
Step 2:Layout the main interface. Add the following controls to the form: Six label controls, four textbox controls, one RichTextBox Control, one checkbox control, one ListBox control, and three button controls. The property settings of each control are shown in the following table:
Form1 (main form) |
Text attributes |
POP3 email receiving program |
Maximizebox attributes |
False |
Label1 |
Text attributes |
POP3 server address: |
Textalign attributes |
Middleright |
Label2 |
Text attributes |
User name: |
Textalign attributes |
Middleright |
Label3 |
Text attributes |
Password: |
Textalign attributes |
Middleright |
Label4 |
Text attributes |
Information: |
Textalign attributes |
Middleleft |
Label5 |
Text attributes |
Email No: |
Textalign attributes |
Middleleft |
Label6 |
Text attributes |
Status: |
Textalign attributes |
Middleleft |
Popserver, username, password, mailnum (Textbox Control) |
Text attributes |
(Both are empty) |
Passwordchar attribute of password |
* |
Message (RichTextBox Control) |
Text attributes |
(Null) |
Backupchbox (checkbox control) |
Text attributes |
Keep backup on the email server |
Status (ListBox control) |
Itemheight attribute |
12 |
Connect (button control) |
Text attributes |
Connection |
Flatstyle attributes |
Flat |
Disconnect (button control) |
Text attributes |
Disconnect |
Flatstyle attributes |
Flat |
Enabled attribute |
False |
Retrieve (button control) |
Text attributes |
Receive email |
Flatstyle attributes |
Flat |
Enabled attribute |
False |
Other attributes can be the default value. After setting the attributes of the preceding controls, make a reasonable layout of the main form to obtain the final interface.
Step 3:Code writing. First, because the program uses some important network programming classes, such as tcpclient and networkstream, you must add the following namespace at the beginning of the program ):
Using system. net;
Using system. net. Sockets;
Using system. IO;
Next, add the following public data members to our class:
Public tcpclient server;
Public networkstream netstrm;
Public streamreader rdstrm;
Publicstring data;
Publicbyte [] szdata;
Publicstring CRLF = "/R/N ";
Finally, there are the message response functions of the three buttons, which are the main part of the program. The message response function of the Connect button completes the connection to the POP3 server and logs on to the server based on the user name and password. If everything goes well, send the STAT command to the server to get the mail Information in the mailbox: the number and size of the mail, and finally complete the connection. The function implementation is as follows:
Privatevoid connect_click (Object sender, system. eventargs E)
{
// Set the cursor to the waiting state
Cursor Cr = cursor. Current;
Cursor. Current = cursors. waitcursor;
// Use port 110 to create a POP3 server connection
Server = new tcpclient (popserver. Text, 110 );
Status. Items. Clear ();
Try
{
// Initialization
Netstrm = server. getstream ();
Rdstrm = new streamreader (server. getstream ());
Status. Items. Add (rdstrm. Readline ());
// Log on to the server
Data = "user" + username. Text + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Status. Items. Add (rdstrm. Readline ());
Data = "pass" + password. Text + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Status. Items. Add (rdstrm. Readline ());
// Send the STAT command to the server to obtain the mail Information: number and size
Data = "stat" + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Status. Items. Add (rdstrm. Readline ());
// Change the button status
Connect. Enabled = false;
Disconnect. Enabled = true;
Retrieve. Enabled = true;
// Set the cursor back to the original state
Cursor. Current = CR;
}
Catch (invalidoperationexception ERR)
{
Status. Items. Add ("error:" + err. tostring ());
}
}
The message response function of the Disconnect button is simple by sending the quit command to the server to terminate the connection with the mail server. The specific function is as follows:
Privatevoid disconnect_click (Object sender, system. eventargs E)
{
// Set the cursor to the waiting state
Cursor Cr = cursor. Current;
Cursor. Current = cursors. waitcursor;
// Send the quit command to the server to end the session with the POP3 server
Data = "quit" + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Status. Items. Add (rdstrm. Readline ());
// Disconnect
Netstrm. Close ();
Rdstrm. Close ();
// Change the button status
Connect. Enabled = true;
Disconnect. Enabled = false;
Retrieve. Enabled = false;
// Set the cursor back to the original state
Cursor. Current = CR;
}
Finally, the message response function of the Retrieve button obtains the corresponding Email based on the user's input in the mail number text box. The command sent to the server is RETR, determine whether or not the email is sent based on the returned information. If the first character of the returned information is "+", it indicates + OK, that is, success. If it is "-", it indicates-err, that is, failure. If the user selects "retain backup on email server", the backup on the server will not be deleted after receiving the email; otherwise, use the DELE command to delete the backup. Function implementation:
Privatevoid retrieve_click (Object sender, system. eventargs E)
{
// Set the cursor to the waiting state
Cursor Cr = cursor. Current;
Cursor. Current = cursors. waitcursor;
String sztemp;
Message. Clear ();
Try
{
// Obtain the corresponding email from the server according to the email number
Data = "retr" + mailnum. Text + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Sztemp = rdstrm. Readline ();
If (sztemp [0]! = '-')
{
// Read the email content continuously, ending only with the English ending sign
While (sztemp! = ".")
{
Message. Text + = sztemp;
Sztemp = rdstrm. Readline ();
}
// If the backupchbox is not selected, the emails retained on the server will be deleted after receiving the emails.
If (backupchbox. Checked = false)
{
Data = "DELE" + mailnum. Text + CRLF;
Szdata = system. Text. encoding. ASCII. getbytes (data. tochararray ());
Netstrm. Write (szdata, 0, szdata. Length );
Status. Items. Add (rdstrm. Readline ());
}
}
Else
{
Status. Items. Add (sztemp );
}
// Set the cursor back to the original state
Cursor. Current = CR;
}
Catch (invalidoperationexception ERR)
{
Status. Items. Add ("error:" + err. tostring ());
}
}
The last step is to save your labor results and then compile, create, and run them. The final illustration is shown at the beginning of the article.
So far, we have completed all the work of the POP3 mail receiving program. From this, it is not difficult to find that it is very easy to use C # to complete some practical network programming. As long as we master the principles, the specific programming work becomes very easy and organized. Even if you didn't know anything about POP3 mail reception in the past, I 'd like to give you a rough idea of it after reading this article. However, it should also be pointed out that this is just a very simple example. If you want to apply it in practice, you still need to make significant improvements. Interested readers may wish to give it a try.