C#_ receiving mail

Source: Internet
Author: User
Tags getstream domain name registration

Implementing a Mail Receiver _ Mail server with Visual C #

In this paper, by usingC #To implement a mail receiving program based on the POP3 protocol to show you the Power of C # Network programming, and to introduce the principle of e-mail reception based on POP3 protocol.

First of all, let me introduce the basic principles of email reception:

At first, the client andServerThe connection. However, before the client connects to the server, note that the port is set to the default number 110th of the POP3 protocol.

After the client connection server succeeds, the server returns the following information:

+ok ...

The character +ok is the return information for the POP3 protocol. Its response information is not the same as the SMTP protocol with the rich and varied numbers, only two: +ok or-err. Where +ok indicates a successful connection, and-err indicates that the connection failed.

Next, the client enters the user < username >

This command tells the server your user name. Note that some servers differentiate between uppercase and lowercase letters.

After the server returns +OK, the client enters pass < password >

After the server returns +OK, it also returns statistics for some mailboxes, such as: +ok 1 message (s) [1304 byte (s)]
The information returned by different servers is not in the same format, so we can use the Stat command to view the mailbox situation. The stat command responds with two numbers, indicating the number of messages and the size of the message, respectively.

If there is a letter in the mailbox, you can use the RETR command to get the text of the message. The format of the RETR command is:

RETR < mail number >

If the first row of the returned result is +ok information, it indicates success. The second line is the body of the message. The last line, like the SMTP protocol, is a separate period that represents the end of the message.

After storing the message to use the DELE command to delete the mail in the mailbox, otherwise the original message will continue to remain on the server, once the mail more, your mailbox exploded. The format of the DELE command is:

DELE < mail number >

If you delete the error, you can use the RSet command to recover all messages that have been deleted. The condition is that you have not quit, once the exit, then all bye bye. When all is done, enter the QUIT command to exit the POP3 server.

Above, I briefly introduce to you the basic process and principle of POP3 mail receiving, below is a Simple mail receiving program which is realized by using the above principle. In this program, I mainly use two classes: the TcpClient class and the NetworkStream class. The TcpClient class is a very important class for network programming using C #, which provides a simple way to connect, send and receive data over the network, thus simplifying the network programming greatly. The NetworkStream class implements the standard. NET Framework flow mechanism for sending and receiving data over a network socket, which supports synchronous and asynchronous access to network traffic and is an important part of implementing network communication. Here I first give the program the final effect of the operation, the diagram is as follows:


Figure 1


The specific process steps are as follows:

First step: Open Vs.net, create a new project, select "Visual C # project" In the project type, select "Windows Application" in the template, the project name may be "Mailreceiver", and finally click "OK" button.

Step two: Layout the main interface. Add the following controls to the form first: Six label controls, four TextBox controls, one RichTextBox control, one CheckBox control, one ListBox control, and three button controls. The properties of each control are set in 1.

After setting up the individual control properties in Figure 1, the main form is properly laid out, and the final interface is as follows:


Figure 2

Step three: Code writing. First, because of the application of some important network programming classes, such as: TcpClient, NetworkStream, so at the beginning of the program to add the following namespace (Namespace):

Using System.Net;
Using System.Net.Sockets;
Using System.IO;


Next, add some of the following public data members for our class:

Public TcpClient Server;
Public NetworkStream NETSTRM;
Public StreamReader RDSTRM;
public string Data;
Public byte[] Szdata;
public string CRLF = "\ r \ n";


Finally, there are three button message response functions, and these three functions are the body part of the program. The message response function of the Connect button completes the connection to the POP3 server and logs in based on the user name and password. If all goes well, then send the stat command to the server to get information about the messages in the mailbox: the number and size of the messages, and finally the connection. Its functions are implemented as follows:

private void Connect_click (object sender, System.EventArgs e)
{
Position the cursor as a wait state
Cursor cr = Cursor.current;
Cursor.current = Cursors.waitcursor;

New POP3 server connection with Port 110
Server = new TcpClient (popserver.text,110);
Status.Items.Clear ();

Try
{
Initialization
NETSTRM = Server.getstream ();
rdstrm= New StreamReader (Server.getstream ());
STATUS.ITEMS.ADD (Rdstrm.readline ());

Logon server procedure
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 a stat command to the server to get information about the mailbox: number and size of messages
Data = "STAT" +CRLF;
Szdata = System.Text.Encoding.ASCII.GetBytes (Data.tochararray ());
Netstrm.write (szdata,0,szdata.length);
STATUS.ITEMS.ADD (Rdstrm.readline ());

Change the state of a button
connect.enabled = false;
Disconnect.enabled = true;
Retrieve.enabled = true;

Place the cursor back in its original state
Cursor.current = CR;

}
catch (InvalidOperationException err)
{
Status.Items.Add ("Error:" +err. ToString ());
}
}


The message response function of the Disconnect button terminates the connection to the mail server by sending the QUIT command to the server, and the function is simple, as follows:

private void Disconnect_click (object sender, System.EventArgs e)
{
Position the cursor as a wait state
Cursor cr = Cursor.current;
Cursor.current = Cursors.waitcursor;

To end and POP3 a session to the server by sending the QUIT command to the server
Data = "QUIT" +CRLF;
Szdata = System.Text.Encoding.ASCII.GetBytes (Data.tochararray ());
Netstrm.write (szdata,0,szdata.length);
STATUS.ITEMS.ADD (Rdstrm.readline ());

Disconnect Connection
Netstrm.close ();
Rdstrm.close ();

Change the state of a button
Connect.enabled = true;
disconnect.enabled = false;
retrieve.enabled = false;

Place the cursor back in its original state
Cursor.current = CR;
}


Finally, the message response function of the Retrieve button obtains the corresponding message according to the user's input in the message number text box, the command sent to the server is RETR, and the message is judged based on the returned information. If the first character of the returned message is "+", then the +ok, that is, the success, or "-" means-err, which is also the failure. In the case of success, if the user chooses "keep backup on mail server", the backup on the server will not be deleted after receiving the message, otherwise the DELE command will be used to delete it. The function is implemented as follows:

private void Retrieve_click (object sender, System.EventArgs e)
{
Position the cursor as a wait state
Cursor cr = Cursor.current;
Cursor.current = Cursors.waitcursor;
String sztemp;
Message.clear ();

Try
{
Get the message from the server based on the message 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 message content continuously, only to the end flag: English period
while (sztemp!= ".")
{
Message.Text + = sztemp;
Sztemp = Rdstrm.readline ();
}

If Backupchbox is not selected, after receiving the message, delete the messages that remain on the server
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);
}

Place the cursor back in its original state
Cursor.current = CR;
}

catch (InvalidOperationException err)
{
Status.Items.Add ("Error:" +err. ToString ());
}
}


The final step is to save your work, then compile, build and run, the final diagram I have given at the beginning of the article, OK.

So far, we have finished all the work of the POP3 Mail receiving program. From this, it is not difficult to find that using C # to complete some network practical programming is very easy. As long as we have mastered the principles, the specific programming work becomes very easy and organized. Even though you didn't know anything about the implementation of POP3 mail reception, I think you'll have at least a general idea of it after reading this article. However, it should be pointed out that this is only a very simple example, if you want to apply in practice, it needs to be greatly improved, interested readers may wish to try. ,
Article collation: Western Digital-Professional to provide domain name registration, virtual hosting services

C#_ receiving mail

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.