In C #. NET implementing e-mail client programs

Source: Internet
Author: User
Tags string back mail exchange

In C #. NET implementing e-mail client programs

Zhou Huaqing Dai (Department of Computer and Communication, Donghua Institute of Technology, Jiangxi Fuzhou 344000)

Digest develops e-mail clients on the. NET platform through the newly introduced object-oriented and type-safe programming language in C #, a visualstudio.net. Through socket programming to achieve network communication connection, the SMTP (Simple Mail Transfer Protocol) and POP3 (Post Office Protocol) Working principle, and then specific to the development of e-mail client based on the SMTP protocol Mail Sender program, according to the POP3 protocol to develop e-mail client mail receiver program.

"keywords" socket Simple Mail Transfer Protocol Post Office Protocol

1 programming of sockets in C #

Sockets are the cornerstone of communication and are the basic operating units that support TCP/IP protocol network communication. Sockets can be seen as endpoints of two-way communication between processes in different hosts, which form a programming interface between a single host and the entire network. Sockets exist in the communication domain. A communication domain is an abstraction that is introduced in order to deal with a generic thread through socket communication. Sockets typically exchange data with sockets in the same domain (data exchange may also traverse the boundaries of a domain, but it is important to perform some sort of interpreter). Various processes use the same domain to communicate with each other using an Internet Protocol cluster.

For socket programming in C # with the socket class, the. NET Framework's socket class is a very important class contained in the System.Net.Sockets namespace, which provides a number of methods for implementing network programming. Using the socket class to develop Windows network applications is a rule-finding, and they follow roughly the same steps in most cases.

Before using it, you need to first create an instance of the socket object, which can be done by constructing the socket class:

Public Socket (addressfamily addressfamily,sockettype sockettype,protocoltype protocoltype);

The AddressFamily parameter specifies the addressing scheme used by the socket, the SocketType parameter, the type of socket specified, and the ProtocolType parameter, which specifies the protocol used by the socket.

The following example statement creates a socket that can be used to communicate on a TCP/IP-based network, such as the Internet.

Socket s = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);

To use UDP instead of TCP, you need to change the protocol type, as shown in the following example:

Socket S=newsocket (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);

Once the socket is created, the client will be able to connect to the specified server via the Connect method and send data to the remote server via the Send/sendto method, which can then receive data from the server via the Receive/receivefrom method; You need to bind the socket to a local endpoint using the Bind method binding, and listen for requests on that interface through the Listen method, and when listening to the client's connection, call accept to complete the connection and create a new socket to handle the incoming connection request. When you are finished using the socket, remember to disable the socket using the shutdown method and close the socket using the Close method.

2 working procedures for SMTP and POP3 protocols

To send/Receive e-Mail on the Internet, two protocols are used: SMTP (Simple Mail Transfer Protocol) and POP3 (Post Office Protocol). Here's how to send and receive e-mail, starting with the SMTP and POP3 protocols.

1, described from the sender using the host (CLIENT1) send a message from the mailbox [email protected] sent to the mailbox [email protected] (where the domain name Server1.com mail system is installed on the Server1, the domain name is server2.com mail system installed on the Server2), the recipient through the host (CLIENT2) receive this message process. Different network protocols are used at all stages of mail delivery.

(1) The sender uses the mail client software to compose an e-mail message to the recipient at Client 1, the first is to send the message from Client1 to his own mailbox [email protected] on the server Server1. This step is sent from Client1 to server using the SMTP protocol.

Figure 1 E-mail delivery process

(2) The Mail can be sent from the sender's mail server Server1 directly to the recipient's mailbox [email protected] on the server Server2, may also need to pass through the third party's mail server Server3 to do the relay and then delivery to the receiving party, This process is called relay. This step uses the SMTP protocol for message delivery between mail servers. After the message is sent to the receiver's server Server2, it is the responsibility of Server2 to post the message to the recipient's mailbox [email protected] , which is saved in the Server2 disk array. At this point, the message delivery process ends.

(3) When the recipient accesses his email address on Server2 [email protected] , use the mail client software Client2 to download the mail from the Server2 mailbox to the local hard drive for reading. This step uses the POP3 protocol to download the message from server to client.

Developing an e-mail client is actually the use of socket programming for conversation communication, which completes the message transfer according to the SMTP protocol and the specification of the POP3 protocol.

3 implementation of the mail sending module

The SMTP protocol is a widely used upper layer protocol in the TCP/IP protocol stack. SMTP defines how messages are transferred between two users, using the concept of spooling, which allows messages to be sent from a local app to an SMTP app. The SMTP app stores the message in a device or in memory, and once the message arrives at the SMTP app, the message is placed in a queue, a server checks to see if a message arrives, and then tries to deliver the incoming message. If the receiver pays of the message does not exist, the server will then try again. Finally, if the message cannot be posted, the message is discarded or returned to the sender of the message. This concept is called end-to-end delivery, and it keeps the message in the queue until the message is posted. We can find a discussion about SMTP from two RFCs. RFC822 describes the structure of the message, which also includes the envelope. RFC821 rules the Protocol for controlling mail exchange between two machines.

The following modules use the TcpClient class to develop an SMTP client to send mail.

3.1 Sending SMTP commands

The SMTP server generally recognizes the UTF8 code, and all Send commands use UTF8 encoding, and each command ends with a carriage return line break. The following code implements the command's send function.

private void Writetonetstream (ref networkstream netstream.string Command)

{String stringtosend = Command + "\ r \ n";

byte[] Arraytosend = System.Text.Encoding.UTF8.GetBytes

(Stringtosend.tochararray ());

Netstream.write (arraytosend,0,arraytosend.length);}

3.2 Acceptance of the Promise code

The SMTP server responds to each one. The following code implements the ability to accept a promise code.

private string Readfromnetstream (ref NetworkStream NetStream)

{byte[] bb=new byte[512];

Netstream.read (BB,0,BB. Length);

String read=system.text.encoding.utf8.getstring (BB);}

3.3 Answer Code Check

The Sending mail client must check the answer code to determine whether the server has executed the command. If the server is not executing, resend the command or take other measures. The following code checks to see if the server executed the command correctly.

private string Checkforerror (string strmessage,string Check)

{if (strmessage.indexof (check) = =-1)

{return "err";}

Else{return "correct";}}

The first parameter of the above method is the server return information, the second parameter is to check the Promise code. If the message returned by the server does not have a string of the second argument, then "Err" is returned, indicating that the server did not execute the command correctly.

3.4 Sending mail

The client issues the data command, and after the server makes a 354 response, it can start sending the message content. The message ends with <CRLF>.<CRLF>. The following code implements the mail sending function.

private void SendMail (ref NetworkStream NetStream, String message)

{byte[] attaytosend = System.Text.Encoding.UTF8.GetBytes

(Message. ToCharArray ());

Netstream.write (arraytosend,0,arraytosend.length);}

4 implementation of the Mail receiving module

Pop allows the local mail UA (user agent, users agents) to connect to the server and take the message back to the user's local system, and the user reads and responds to the message on the local machine. The Pop3ua is connected to the server via TCP/IP (typically using port 110). After the user name and password have been entered for authentication, UA can retrieve or delete the message via the POP3 command. POP3 is just the receiving protocol. Pop3ua uses SMTP to send mail to the server.

Use the POP3 protocol to develop a mail receiving program that uses user, PASS, STAT, LIST, RETR, DELE, quit commands. The development process begins below.

4.1 Send command code

This command code is also used in ASCII code. The following methods are used to send command codes to the server:

private void Writetonetstream (ref networkstream netstream.string Command)

{String stringtosend = Command + "\ r \ n";

Byte[]arraytosend= System.Text.Encoding.ASCII.GetBytes

(Stringtosend.tochararray ());

Netstream.write (arraytosend,0,arraytosend.length);}

4.2 Receive Server Answer

In general, the receiving server answers, either using ASCII code or using the UTF8 code, where ASCII code is used. The following methods are used to accept server replies.

private string Readfromnetstream (ref NetworkStream NetStream)

{byte[] bb=new byte[1024];

Netstream.read (BB,0,BB. Length);

String read=system.text.encoding.ascii.getstring (BB);

return read;}

4.3 Accept Mail

In this receive mail with UTF8 code, when encountered <crkf>.<crlf>, then end reading data. The following code is used to receive mail:

private void Readmail (ref networkstream netstream,int number)

{int k=0;

BOOL Check=false;

Byte[] Bb=new byte[6400];

while (!check)

{K=netstream.read (BB,0,BB). Length);

String read=system.text.encoding.utf8.getstring (Bb,0,k);

int x= read. IndexOf ("\r\n.\r\n");

if (x!=-1)

{check=true;}

Richtextbox2.appendtext (read);

Writetonetstream (ref

NetStream, "DELE" +number. ToString ());

String Back=readfromnetstream (ref NetStream);

Richtextbox1.appendtext ("DELE" +number. ToString ()

+ "command answer:" +back+ "\ r \ n"); }}

5 concluding remarks

By combining the mail sending module with the mail receiving module, it becomes an email client program. In the practical application, on the basis of the improvement, if further combined with the database technology, this can develop an easy-to-use, reliable e-mail client program.

(Received: 2004-02-25; e-mail:[email protected])

 

Programming e-mail client with c#.net

Abstract:develop a program for e-mail client on the flat in. NET with C #. C # is a new language of Visual Studio. NET, was modern, object-oriented and is safe in type. Realize the network correspondence depending Socket programming. Expatiate the principle of SMTP (simple Mail Transfer Protocol) and POP3 (Post office Protocol), then explain developing a P Rogram to send e-mail according to the SMTP agreement development email Mail Customer and carry to receive the procedure Developing a program to receive e-mail according to the POP3 in detail.

Key Words:socket; Simple Mail Transfer Protocol; Post Office Protocol

Reference documents

[1] Shehiren. Network. 2nd edition. Beijing: Tsinghua University Press, 1999

[2] Charles Petzold. Windows programming. 5th edition. Beijing: Peking University Press, 1999

[3]  Anthony Jones and Jim Ohlund. Windows network programming. 2nd edition. Beijing: Tsinghua University Press, 2002

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.