Understand the POP3 protocol, use simple code monitoring POP3 mailbox

xiaoxiao2021-03-06  41

POP3 protocol points, more detailed information can be viewed RFC1939

(1) The POP3 command consists of a command and some parameters. All commands are composed of a CRLF pair (2) command and parameters consisting of a printable ASCII character, and they consist of a status code and a command that may follow additional information between the Space Space (3) POP3. All responds are also two state codes, "determination" (" OK") and "fail" ("-err"). ("-Err") by the CRLF end (4). (5) When all the information is transmitted, the last line is transmitted, including an end character (decimal code 46, that is, ") and a CRLF pair. (6) There are three states, accredited status, processing status, and update status in the POP3 protocol. When the client is connected to the server, once the client provides its own identity and successfully confirmed, that is, the client issues a Quit command after the corresponding operation is transferred, then the client issues a Quit command, then enter the update state, after the update is finally heavy State the state. As shown below

Waiting to connect to identify Quit Commands - | Approve | ----- | Process | ------ | Update | | | _________________________________ | Return

A minimal, successful client-server session process

POP3 Client Pop3 Server Socket () Listen () Connect () -------------------------------> accept () <- ---------------------------- OK Send a confirmation message (enter "confirm" status) Send a user command ------ ------------------------> <------------------------ ----- OK Send a confirmation message Send pass command ----------------------------> <----- ------------------------ OK Send a confirmation message (enter the "operation" status) Send a quit command ----------- ------------------------------------------------------------------- OK Send a confirmation message (enter "update" status) If the customer sends quit in the "confirmation" state, the session does not enter the "update" state

You can test it in the command line (cmd.exe): c: / telnet pop3.163.com 110 // Connect to Netease's mail server OK Coremail .... // Return OK User 'YourUsename' // Customer The end issued a username, and a pair of single quotes pass 'YourPassword' // clients may issue a password on Your Assam. You may need a pair of single quotes OK mm nn // on YourPassword to return the number of emails and size stat // get the mailbox Status OK XXX XXX // Returns the number of commands and the commands you can send by the size, from ChinaUnix

Command parameter status description --------------------------------------------- -------------------------------------------------- ---------------------------------------------------------------------------------------------------- The following pass command will result in status to convert Pass Password approved APOP NAME, DiGest approved Digest is MD5 message summary, Windows system is not supported -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- -------- ------------------------------------------------------------------------ ----------------------------------------- Stat None handling request server sent back to mailbox Statistics, such as the total number of mails and total bytes UIDL [MSG #] to process the unique identifier of the message, each identifier of the POP3 session will be the only list [msg #] process returns the number of emails and each message The size retr [msg #] process returns the full text dele [msg #] processing server that is identified by the parameter identifier to mark the message identified by the parameter to delete, and execute the RSET NONE processing server by the quit command will reset all tagged messages. Used to revoke the dele command TOP [MSG #] Processing server will return to the N-line content of the message identified by the parameter, n must be the positive integer NOOP NONE processing server to return a positive response ------------ -------------------------------------------------- -------------------------------------------------- -------------- Quit None update

Foxmail and Outlook Use POP3 from POP3 from LinuxForum.net hypothesized that there are three emails on the server waiting to receive. The difference between Foxmail and OE is to delete an additional marking in Foxmail, while Outlook, etc., then fully marked to delete the final execution Quit command. Foxmail Outlook ------------------------------------------ RETR 1 Retr 1 dele 1 Retr 2 Retr 2 Retr 3 Dele 2 Dele 1 Retr 3 Dele 2 Dele 3 Dele 3 Quit Quit --------------------------- -------------- Simple C # code to implement POP3 mailbox monitor Namespace sky.mailmonitor {public class pop3 {private const into = 1024; // default 1kbytes buffers

// Server confirm the status code of the message, must be uppercase private const string okflag = " ok"; private const string errflag = "-err"; private int _port = 110; public int port {get {return_port;

Set {_port = value;}} private int mailcount = 0; public int mailcount {get {return mailcount;} set {mailcount = value;}}

PRIVATE INT mailspace = 0; public int mailspace {get {return mail = value;}}

Private socket socket = null; public int port;}} // Step 1: Connect a pop3 server, I hope to get a 1-OK confirm message public void connection (String hostname) {// Create a socket Socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPHostEntry hostInfo = Dns.GetHostByName (hostname); IPEndPoint endPoint = new IPEndPoint (hostInfo.AddressList [0], Port);

Socket.connect (endpoint); string tmp = recvline (); // blocking, wait for ' ok' console.writeline (TMP);} // Step 2: Send a command word User and Pass public void login (String Username, String password) {Sendcommand ("User" UserName); string tmp = recvline (); console.writeline ("Server Say: {0}", TMP);

SendCommand ("Pass" password); string tmp1 = recvline (); console.writeline ("Server Say: {0}", TMP1);} // Step 3: Send a command word Stat, request the server to send back to the mailbox Statistics, such as the total number of mails and total bytes // c: stat // s: OK nn mm // nn is the number of emails, mm is the size of public void stat () {sendcommand ("stat"); string tmp = Recvline (); tmp = tmp.substring (tmp.indexof ("") 1); // Get the number of emails after ok and a space, byte String Tmp1 = Tmp.Substring (0, TMP.Indexof) "")). Trim (); mailcount = int32.Pars (Tmp.Substring (0, tmp.indexof (")). Trim ()); console.writeline (" Server Say: {0} ", TMP) ; // mailspace = int32.parse (Tmp1.Substring (0, tmp1.indexof (")). Trim ());} // list [msg], the MSG parameter is optional, return the number of emails and each The size of the message, if there is no MSG parameter, the server will return all mail information // c: list // s: OK 187 9703827 // 3 1826 //. Public void list () {Sendcommand ("List"); string tmp = recvline (); Console.writeline ("Server Say: {0}", TMP);} public void de (String mailnumber) {sendcommand ("dele" mailnumber; string tmp = recvline (); console.writeline ("Server SAY: {0} ", TMP);

Public void Quit () {Sendcommand ("quit"); string tmp = recvline (); console.writeline ("Server Say: {0}", TMP);}

// / / Close the open connection and send the quit command word, the quit command does not have the parameters public void close () {if (socket == null) return; try {quit (); // first invoke quit method} finally {socket. Close ();}} private void sendcommand (String command) {command = ""; // must add CRLF to Byte [] buffer = Encoding.ascii.getBytes (Command.tochararray ()); // Send buffer int Bytessent = socket.send (buffer, buffer.length, 0); if (bytessent! = Buffer.length) throw new exception ("failed to send request to server);} // Todo: server with Multi LINE Answer Private String Recvmultiline () {} // Server Answer Private String Recvline () in line CRLF () {// Need to add an empty terminator Byte [] buffer = new byte [buffs 1]; stringbuilder message = new StringBuilder (bufsize); INT BYTESREAD; // Read buffer for (;;) {bytesread = socket.receive (buffer, bufsize, socketflags.none); // reads finish (BytesRead == 0) Break; buffer [bytesread] = 0 ;

// Conver char Array to string message.Append (buffer, 0, bytesread); if (buffer [bytesread - 1] == 10) // = lf #hex: 0a #dec: 10 Break String tmp = message.toString (); if (tmp.startswith (okflag) == false) // server message is not a confirmation message at OK {ThROW (New Exception (TMP));} Return TMP; }}} The above code has completed the basic function of monitoring, but it is not enough. First, there is no abnormality processing, such as where the connection fails, the connection failed? Second, if you want to receive the email, then characters Coding is a problem, especially the process of Chinese characters, more troubles, detailed information can be viewed. You can improve the basic code, realize local POP3, now you can test: use management system; useing system; using system; using System.collections.Generic; Using System.Text;

#ndregion

namespace Sky.MailMonitor {class Program {static void Main (string [] args) {Pop3 pop3 = new Pop3 (); string username = "xxxxxx"; string password = "xxxxxx"; string hostname = "pop3.163.com" Try {pop3.connect (hostname); pop3.login (username, password); pop3.stat (); pop3.list ();} catch (exception e) {console.writeline (E.MESSAGE);} finally { POP3.Close ();}}}

转载请注明原文地址:https://www.9cbs.com/read-55071.html

New Post(0)