1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu SMTP and POP3 doc

26 348 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 26
Dung lượng 0,9 MB

Nội dung

5 SMTP and POP3: Communicating with email S er v ers 5.1 Intr oduction M or e emails ar e sent ev er y day than postal mail. Why? B ecause email is cheap , informal, fast, and can be picked up at the r eceiv er ’ s conv enience. E mails can be automatically generated and sent, making them ideal for automated status notification. O ne day , y ou may r eceive an email fr om y our home sprinkler system saying simply , “ Y our house is on fir e.” After r eading this chapter y ou will be able to send and r eceive emails fr om y our .NET applications. These featur es can be useful for customer suppor t systems, collaborativ e personnel management, and many other types of applications. This chapter begins b y describing ho w emails can be constr ucted and sent, using either a socket-lev el appr oach, or b y using in-built .NET classes. I mmediately follo wing that, is a description on ho w emails may be r eceiv ed, again, b y either using a socket lev el appr oach, or a higher-lev el methodol- ogy , lev eraging M icr osoft O utlook. 5.2 Sending an email E v er y email must hav e a destination email addr ess. An email addr ess takes the follo wing form: < Username >@< domain name > The domain name in an email addr ess generally does not include the “www” pr efix, which is common for W eb site addr esses. D espite that, the domain name is globally r ecogniz ed under the DNS system. The username is r ecogniz ed only b y the r ecipient mail ser v er . E mails ar e not immediately deliv er ed to the r ecipient; instead, they ar e initially sent to y our ISP’ s or company ’ s mail ser v er . F rom ther e, they ar e for war ded to the r ecipient ’ s mail ser v er or held for a period of time until the r ecipient ’ s mail ser v er accepts the email. E mails ar e sent using the simple mail transfer pr otocol (SMTP), which is described in detail later . I n or der to determine the r ecipient ’ s mail ser v er , a DNS mail ex change (MX) quer y is issued to the local DNS ser v er for that domain name. That computer will then r eturn details of wher e the ser v er or ser v ers that handle incoming mail ar e located. N ote: M ost ISP s hav e only one incoming mail ser v er , but H otmail.com has mor e than 10 mail ser v ers. Y ou will always be told the IP addr ess of y our SMTP ser v er . U nfor tu- nately , y ou cannot use an SMTP ser v er fr om another ISP because it will block y ou with an err or message such as “R elaying denied.” M icr osoft vir tual SMTP ser v er is av ailable for most v ersions of W in- do ws and generally appears under IIS when installed. 5.2 SMTP SMTP is used to send, but not r eceiv e, emails. E v er y mail ser v er in the world must conform to the SMTP standar d in or der to send emails r eli- ably r egar dless of destination. The definitiv e guide to SMTP is held b y the I nternet E ngineering T ask F or ce (IETF) under RFC 821 at www .ietf.org/ r fc/r fc0821.txt. The definitiv e guides to most major pr otocols ar e held at the IET F . They ar e fr ee to do wnload and should be consulted when y ou ar e dev elop- ing networ k applications that ar e designed to wor k with pr eexisting or thir d-par ty clients or ser v ers. SMTP is not a difficult pr otocol to implement fr om the gr ound up; ho w ev er , it is nativ ely suppor ted fr om .NET and, thus, would be a waste of time to r edev elop . Also, many commer cial email components ar e av ailable, which can be imported into y our application. O ne of the most popular is AspE mail fr om P ersits S oftwar e. The demo v ersion of this component is adequate for most applications. 5.3.1 Implementing SMTP SMTP operates on T CP por t 25. B efor e sitting do wn to code, y ou should first find out the IP addr ess of y our ISP’ s SMTP ser v er . I n the examples belo w , the SMTP ser v er smtp.ntlworld.com is used. Y ou should r eplace this with y our o wn SMTP ser v er , or the examples will not wor k. SMTP was originally designed for UNIX users and has a command- line- type feel to it, although the commands ar e issued o v er a networ k con- nection, rather than a keyboar d. A good way to test the pr otocol is to open telnet b y clicking S tar t → Ru n and type telnet. I n W indo ws NT , 2000, and X P , type o smtp.ntl- world.com 25. I n prior v ersions of W indo ws, click F ile → Connect, and then type smtp.ntlworld.com into the connection bo x and 25 into the por t bo x. Then pr ess Connect. O nce the client establishes a T CP connection to the ser v er on por t 25, the ser v er will always r eply with 220 < some greeting message ><enter>. A number is always included at the star t of ev er y ser v er r esponse. Any number beginning with 5 is an err or and should be dealt with; ev er ything else can be ignored. The client must then send a gr eeting back to the ser v er . This is mer ely a formality and does not contain any useful information. The format is HELLO server <enter>, and the ser v er should r eply with 250 server <enter>. The next step is to send a contact email addr ess for the sender . This is sent in the format MAIL FROM:< email address ><enter>. The ser v er should r eply 250 OK<enter>. F ollowing that, the r ecipient must be indicated. T o do this, RCPT TO:<email address><enter> is used. The ser v er should r eply 250 OK<enter>. T o cr eate the body of the email, the client sends the command DATA<enter>. T o this the ser v er should r eply 354 < some instruc- tions ><enter>. The client can then send as much text as r equir ed to make up the body of the email. I t is r ecommended to split the mail o v er sev eral lines because of r estrictions in some mail ser v ers. T o indicate the end of the mail body , send <enter>.<enter>. The ser v er should r eply 250 OK<enter>. A t this point, it is possible simply to close the T CP connection, but it is r ecommended to send QUIT<enter>. The follo wing passage sho ws the chain of ev ents between client and ser v er when an email is sent fr om smith@usc- isif.arpa to jones@bbn-unix.arpa. “S” indicates a transmission fr om ser v er to client, and “C” indicates a client-to-ser v er transaction. S: 220 Simple Mail Transfer Service C: HELO SERVER S: 250 SERVER C: MAIL FROM:<Smith@USC-ISIF.ARPA> S: 250 OK C: RCPT TO:<Jones@BBN-UNIX.ARPA> S: 250 OK C: DATA C: 354 Start mail input; end with <CRLF>.<CRLF> C: Dear sir C: Please give me a call to discuss your offer C: . S: 250 OK C: QUIT S: 221 CLOSED Example: Complaints depar tment SMTP ser v er I f y ou ev er wor k in the complaints depar tment of a company , this applica- tion will make y our life a lot easier . I t mimics the communications an SMTP ser v er would make, but it thoughtfully ignor es the email content, saving y ou a lot of str ess. O f course, a r eal application would be to hav e it log the emails to a data- base, but, for the sake of clarity , that featur e is not included in this example. P ossible deriv ations of this pr oject could be an email pr o xy ser v er , which could filter emails for viruses, and so for th. S tar t a C# or VB.NET W indo ws form pr oject as usual, and drag a text- bo x onto the form. Call it tbStatus, and set multiline to true. T o star t with, w e must impor t all of the namespaces w e intend to use in this application. P ut this code at the beginning of the pr ogram: C# using System.Threading; using System.Net; using System.Net.Sockets; using System.Text; VB .NET Imports System.Threading Imports System.Net Imports System.Net.Sockets Imports System.Text F or simplicity , this ser v er will be single thr eaded. The thr ead that listens for incoming connections r uns in the backgr ound and starts when the form loads. This means that, although the pr ogram won ’ t hang waiting for con- nections, it can only handle one email at a time. C# private void Form1_Load(object sender, System.EventArgs e) { Thread thdSMTPServer = new Thread(new ThreadStart(serverThread)); thdSMTPServer.Start(); } VB .NET Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim thdSMTPServer As Thread thdSMTPServer = New Thread(New ThreadStart( _ AddressOf serverThread)) thdSMTPServer.Start() End Sub This thr ead pr o vides the functionality to r eceive emails sent via SMT P . I t listens on por t 25 and blocks until an incoming connection is detected. This connection is accepted, and a 250 hello<enter> r eply is sent back to the client. N ote that her e it is possible to use ASCII.GetBytes because SMTP is a text- based pr otocol, and binar y content is not sent at this lev el. The function socketReadLine is not defined y et, but its purpose is to stor e incoming data in a string until the termination character(s) is found. D ata returned fr om the client is display ed in tbStatus, but no other pr ocessing takes place. C# public void serverThread() { Byte[] sendBytes; TcpListener tcpListener = new TcpListener(25); tcpListener.Start(); while(true) { Socket handlerSocket = tcpListener.AcceptSocket(); if (handlerSocket.Connected) { // Reply 250 hello sendBytes = Encoding.ASCII.GetBytes("250 hello\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); // Wait for enter (hello) tbStatus.Text += socketReadLine(handlerSocket,"\n"); // Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); // Wait for enter (mail from) tbStatus.Text += socketReadLine(handlerSocket,"\n"); // Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); // Wait for enter (rcpt to) tbStatus.Text += socketReadLine(handlerSocket,"\n"); // Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); // Wait for enter (data) tbStatus.Text += socketReadLine(handlerSocket,"\n"); // Reply 354 sendBytes = Encoding.ASCII.GetBytes("354 proceed\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); // Wait for enter.enter (email body) tbStatus.Text += socketReadLine(handlerSocket, "\r\n.\r\n"); // Reply 221 close sendBytes = Encoding.ASCII.GetBytes("221 close\n"); handlerSocket.Send(sendBytes,0, sendBytes.Length,SocketFlags.None); handlerSocket.Close(); } } } VB .NET Public Sub serverThread() Dim sendBytes As Byte() Dim tcpListener As New TcpListener(25) Dim handlerSocket As Socket tcpListener.Start() Do handlerSocket = tcpListener.AcceptSocket() If handlerSocket.Connected = True Then ' Reply 250 hello sendBytes = Encoding.ASCII.GetBytes("250 hello" + vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) ' Wait for enter (hello) tbStatus.Text += socketReadLine(handlerSocket, vbCrLf) ' Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok" + vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) ' Wait for enter (mail from) tbStatus.Text += socketReadLine(handlerSocket, vbCrLf) ' Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok" + vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) ' Wait for enter (rcpt to) tbStatus.Text += socketReadLine(handlerSocket, vbCrLf) ' Reply 250 ok sendBytes = Encoding.ASCII.GetBytes("250 ok" + vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) ' Wait for enter (data) tbStatus.Text += socketReadLine(handlerSocket, vbCrLf) ' Reply 354 sendBytes = Encoding.ASCII.GetBytes("354 proceed" + _ vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) ' Wait for enter.enter (email body) tbStatus.Text += socketReadLine(handlerSocket, _ vbCrLf + "." + vbCrLf) ' Reply 221 close sendBytes = Encoding.ASCII.GetBytes("221 close" + vbCrLf) handlerSocket.Send(sendBytes, 0, sendBytes.Length, _ SocketFlags.None) handlerSocket.Close() End If Loop End Sub This thr ead starts b y listening on por t 25 for incoming connections. The thr ead blocks on the call to AcceptSocket() and waits indefinitely until a connection arriv es. O nce a connection arriv es, it is stor ed in a socket object named handlerSocket. O nce the connection is established, the ser v er immediately r esponds with 250 hello. The ser v er then waits for the client to r espond. I n r esponse to ev er y command sent b y the client, the ser v er r esponds with 250 ok. The client is then expected to send a mail from com- mand, and the ser v er will wait until the client does so . O nce the ser v er has r eplied, it will wait for a rcpt to command and finally a data command. The ser v er will r ead in data fr om the socket until the end-of-message mar ker (a period on a line b y itself ) appears. The ser v er then pr ompts the client to close the connection befor e closing the connection itself . The socketReadLine function is called many times fr om serverThread. I t takes a socket and a terminator string as parameters. Again, it r eads in fr om the networ k str eam one b yte at a time and builds up the streamData string. I f the terminator string appears in the streamData string, or if Read- Byte fails because of a networ k err or , then the function r eturns. C# public String socketReadLine(Socket socket,String terminator) { int lastRead=0; String streamData = ""; NetworkStream networkStream = new NetworkStream(socket); do { lastRead = networkStream.ReadByte(); if (lastRead==-1) break; streamData+=(Convert.ToChar(lastRead)); if (streamData.EndsWith(terminator)) break; } while(true); return streamData; } VB .NET Public Function socketReadLine(ByVal socket As Socket, _ ByVal terminator As String) As String Dim lastRead As Int16 Dim streamData As String Dim networkStream As New NetworkStream(socket) Do lastRead = networkStream.ReadByte() If lastRead = -1 Then Exit Do streamData += (Convert.ToChar(lastRead)) If streamData.EndsWith(terminator) Then Exit Do Loop Return streamData End Function The socketReadLine function may look a little v erbose, especially because the StreamReader alr eady has a ReadLine method; ho w ev er , this function is designed to be generic enough such that it can detect both ne w-line ( \n or vbcrlf ) message terminators and end-of-message mar kers (a period on a line b y itself ). This function cr eates a NetworkStream to the socket and then r eads fr om the str eam one b yte at a time, appending the b yte to a string, which is returned once the message terminator has been found. B efor e r unning this example, ensur e that no other SMTP ser v er is r un- ning at the same time. Y ou can check for the default vir tual SMTP ser v er b y opening IIS fr om A dministrativ e T ools and expanding y our local computer name fr om within the console. Y ou can stop the SMTP ser v er (if it is installed) b y right-clicking on its icon and selecting stop . F igure 5.1 M icr osoft O utlook, new account. T o test this example, r un it fr om V isual S tudio .NE T . Then open an email pr ogram (e.g., M icr osoft O utlook). P r ess T ools → A ccounts (Figur e 5.1), then click A dd → M ail, and click N ext twice. T ype anything in the POP3 bo x, and type the IP addr ess of the com- puter on which y ou ar e r unning the SMTP S er v er , or 127.0.0.1 if y ou only hav e one computer . Keep pr essing N ext until y ou arriv e back at the pr evious scr een. C r eate a ne w email as usual, and select y our ne w account to send fr om. O n O utlook, this is selected fr om an arr o w to the right of the S end button; on O utlook Expr ess, this is selected fr om a dr op-do wn list in the “ to ” field. N o w pr ess S end. Y ou will see the raw T CP data written as text in the application ’ s win- do w , as sho wn in Figur e 5.2. 5.4 P ost office pr otocol 3 P ost office pr otocol 3 (POP3) is used to r eceiv e, but not send, emails. E v er y ISP has a POP3 ser v er , and many W eb hosting companies offer access to a F igure 5.2 SMTP ser v er application. POP3 ser v er to pr o vide personaliz ed email addr esses such as joeD oe@exam- ple.com (fictitious). POP3 is described definitiv ely in RFC 1939, which is do wnloadable at www .ietf.org/r fc/r fc1939.txt and operates on T CP por t 110. POP3 is used to stor e emails on behalf of users. U sers can then do wn- load these emails selectiv ely fr om the ser v er . S ome ser vice pr o viders limit the amount of space dev oted to any one user on a POP3 ser v er . Ther efore, POP3 also facilitates message deletion. Again, befor e r ushing into implementing POP3, be awar e that ther e ar e alternativ es; for instance, y ou can use M icr osoft E x change as a POP3 ser v er , and commer cial components b y IP*W or ks or S oftArtisans can be used as POP3 clients. 5.4.1 Implementing POP3 Like SMT P , POP3 is a command-line-based pr otocol, wher e each line is terminated with a line-feed ( <enter> ) character . F or v ariable length lines, the command is terminated b y <enter>.<enter> as in SMT P . When the ser v er is operating normally , each line will star t with +OK. I f an err or occurs, the line begins with –ERR < some explanation >. O nce the client establishes a T CP connection to the ser v er on por t 110, the ser v er will always r eply with +OK < some greeting message ><enter>. T o access a mailbo x, the client must authenticate itself with a username and passwor d. The client sends USER < username ><enter>. The ser v er then r eplies with +OK <welcome><enter>. The passwor d is sent as USER < pass- word ><enter> with the same r esponse fr om the ser v er . T o get summar y information about the mailbo x, the command STAT<enter> is issued. T o this the ser v er will r eply +OK < number of mes- sages > < total size ><enter>. U nlike the pr evious messages, wher e the text after the +OK could be ignored, her e it must be r ead and stor ed for futur e use. T o r ead back an email, the client sends the RETR < number > command; Number must be between 1 and the number r eceiv ed in r esponse to the STAT command. The ser v er will r espond +OK < some message ><enter>< mail body ><enter>.<enter>. The only piece of impor tant information is the mail body; ev er ything else can be ignored. T o delete emails, the client sends the DELE < number > command. The ser v er will r espond +OK < some message ><enter>. A t this point, it is possi- ble simply to close the T CP connection, but it is r ecommended to send QUIT<enter>. T o illustrate the pr otocol mor e simply , the follo wing text sho ws the chain of ev ents that occur between a POP3 ser v er and client. As befor e, “S” indicates a transmission fr om ser v er to client, and “C” indicates a client-to- ser v er transaction. H ere, user Bob is checking his emails, when he r eceiv es two messages fr om Alice and T err y . S: +OK POP3 server ready C: USER bob S: +OK user valid C: PASS secret S: +OK pass valid C: STAT S: +OK 2 170 [...]... Visual Studio NET, and the contact’s name and email address will appear as shown in Figure 5.7 Figure 5.7 MAPI address book application 5.6.2 IMAP The Internet message access protocol (IMAP) runs over port 143 and is described definitively in RFC 1730 Although SMTP and POP3 are the de facto standards for email com- munication on the Internet, they are both very simple protocols, and some contenders... of a MailMessage object and passes it to the SmtpMail object To test the application, run it from Visual Studio NET Fill in your own email address in the “To:” field, your SMTP server in the “Server” field, and then fill in whatever you wish in the other fields and press Send A few moments later, check your email, and you should have received the message (Figure 5.5) Figure 5.5 SMTP client application... email.Body = tbMessage.Text; SmtpMail.SmtpServer = tbServer.Text; SmtpMail.Send(email); } VB.NET Private Sub btnSend_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnSend.Click Dim email As New MailMessage() With email From = tbFrom.Text To = tbTo.Text Subject = "email from NET" Body = tbMessage.Text End With SmtpMail.SmtpServer = tbServer.Text SmtpMail.Send(email) End Sub... connection Goodbye 5.7 Conclusion This chapter has explained how to send and receive emails from your NET application, either from high-level code or socket-level operations This chapter outlined the key facets of SMTP and POP3, in summary: SMTP is used to send emails from client to server POP3 is used to receive emails from server to client POP3 can be used to delete emails from the server once received Chapter... sends the specified command to the POP3 server and reads back data until it encounters the end-of-line marker \r\n or vbCrLf The data that is read back is displayed on screen and returned to the calling function To test this application, run it from Visual Studio NET Type your POP3 server’s IP address into the field provided You will also need to pro- vide your email account username and password Using... collection Each entry in the latter collection contains a Name and Address property that can be used to extract email addresses and proper names from the Outlook address book To create an application that reads the Outlook address book, reopen the example shown above and alter the column headers to read Alias and email address Now click on the form and enter the following code: C# private void Form1_Load(object... the text to the bottom, you will see the POP3 command DELE, signi- fying that the email was deleted as shown in Figure 5.3 5.5 System.Web.Mail There is a built-in mechanism for Windows 2000 and later to send emails This is called CDOSYS (Microsoft Collaboration Data Objects for Win-dows 2000) It is much simpler than implementing SMTP, especially where attachments and rich-text emails are involved; however,... runs over port 119 and is described definitively in RFC 977 This protocol is used for efficient management of mailing lists and is gradually becoming obsolete and being replaced by email-based systems It is based on the idea that many users can send and receive undirected email, which is sorted into subjects of interest Two basic tasks can be performed with NNTP: reading postings and creating new postings... a newsgroup, a client connects to the news server and retrieves a list of newsgroups by using the LIST command To select a group, the client issues the GROUP command fol- lowed by the group name The server response to this command includes the number of messages stored for that group To download one of these messages, the client sends the STAT command, followed by the message number To view the downloaded... Reference, and then click on the DLL (Figure 5.4) System.Web.Mail With that, you can draw your GUI Drag three textboxes onto the form, name them tbTo, onto the form, name it tbMessage, and set form, and name it btnSend tbFrom, and tbServer Drag another textbox multiline to true Finally, place a but- ton on the C# using System.Web.Mail; VB.NET Imports System.Web.Mail Now click on the Send button and type . SMTP ser v er is av ailable for most v ersions of W in- do ws and generally appears under IIS when installed. 5.2 SMTP SMTP . y our o wn SMTP ser v er , or the examples will not wor k. SMTP was originally designed for UNIX users and has a command- line- type

Ngày đăng: 27/01/2014, 14:20

TỪ KHÓA LIÊN QUAN

w