C # basics-POP3-based Mail receiving and STMP-based mail sending,

Source: Internet
Author: User
Tags mail exchange mailmessage smtpclient

C # basics-POP3-based Mail receiving and STMP-based mail sending,

Recently, emails are synchronized with outlook. I am interested in the email protocol. So I collected some information and learned how to use. net to send and receive emails.

  

I. SMTP protocol

    1. What is SMTP protocol:

SMTPCurrentlyInternetTransmissionEmailIs a relatively simple text-based protocol. One or more receivers of a message are specified on top of the message (which is determined to exist in most cases), and the message text is transmitted. You can easilyTelnetProgram to testSMTPServer,SMTPUseTCPPort 25. Determine a domain name for a given domain nameSMTPServer, need to useMX (Mail eXchange) DNS. (From Baidu encyclopedia)

2. How to implement:

To implement the SMTP protocol ,. net provides the MailMessage class for storing mail information (including the subject, sender address, recipient address, and attachment, including the mail format [text, HTML...]. SmtpClient class to implement Protocol connection. StmpClient provides two parameters: stmp and port. You can query the protocol and port number on the Internet. Common email Port:STMP default 25. The implementation code is as follows:

Public static bool SendEmail () {try {MailMessage msg = new MailMessage (); msg. from = new MailAddress (fromEmailAddress); // sender's email msg. subject = "emails from Xiaocong"; msg. body = "Have you eaten today, Xiaoqiang"; msg. bodyEncoding = System. text. encoding. default; msg. to. add (toEmailAddress); // recipient address. You can Add multiple SmtpClient clients = new SmtpClient (smtp, port); // smtp = "smtp.qq.com"; port = 25 QQ mailbox client. credentials = new System. net. networkCredential (msg. from. address, password); client. deliveryMethod = SmtpDeliveryMethod. network; client. send (msg);} catch (Exception ex) {return false;} return true ;}

Ii. POP3 protocol:
1. What is POP3 protocol:

Post office agreement(Post Office Protocol, AbbreviationPOPIs a member of the TCP/IP protocol family, defined by RFC 1939. This Protocol is mainly used to support remote management of emails on the server using the client. The latest version isPOP3The full name is "Post Office Protocol-Version 3", and the POP3 Protocol that provides SSL encryption is calledPOP3S. (From Wikipedia)

2. How to implement:

To perform mail operations. You only need to abide by the corresponding command protocol. For general operations. You must first pass the user and pass verification. After the verification is successful. To run the following commands.

Command Description
User User Name
Pass Password. After executing the command, you can get the number of mails and the total number of bytes of mails.
Apop A Secure Password transmission method. digest is the md5 message digest, which leads to status conversion after successful execution.
Stat The request server sends back the mailbox statistics, such as the total number of mails and the total number of bytes.
Uidl The unique identifier of the returned message. Each identifier of a pop3 session will be unique.
List Number of returned mails and the size of each email
Retr Returns all text of the emails identified by parameters. retr + 5 indicates that the text of the first five emails is returned, but the returned information is garbled and needs to be transcoded.
Dele The server marks the emails marked by parameters as deleted and is executed by the quit command.
Rset The server resets all emails marked as deleted to cancel the dele command.
Top The server returns the content of the first n lines of the email identified by parameters. n must be a positive integer.
Noop The server returns a positive response without any operation.
Quit Exit

For more convenient understanding, see the following code: For each sr. Readline command, if it is obtained successfully. There will be a "+ OK" in the read string. You can determine whether the string contains OK and whether the command operation is successful (I ignored it in the Code ). secondly, for the RERT command. Garbled characters are returned. Transcoding is required. This will be updated in the follow-up blog.

NOTES:The pop3 port number is 110 by default, and the code has a good wide port. Account password, which is a static variable of the class. Not displayed.

Public static void GetMessage () {TcpClient Server = new TcpClient (pop3, pop_port); // Tcp NetworkStream netSream = Server. getStream (); StreamReader sr = new StreamReader (netSream); byte [] byData; string data; try {string str = string. empty; data = "USER" + fromEmailAddress + "\ r \ n"; byData = System. text. encoding. ASCII. getBytes (data. toCharArray (); netSream. write (byData, 0, byData. length); Console. writeLine (sr. readLine (); data = "PASS" + password + "\ r \ n"; byData = System. text. encoding. ASCII. getBytes (data. toCharArray (); netSream. write (byData, 0, byData. length); Console. writeLine (sr. readLine ());
Data = "STAT" + "\ r \ n"; byData = System. text. encoding. ASCII. getBytes (data. toCharArray (); netSream. write (byData, 0, byData. length); Console. writeLine (sr. readLine (); Console. writeLine ("link successful... ");} catch (Exception ex) {Console. write ("link server failed... "); return;} try {data =" RETR "+ 5 +" \ r \ n "; byData = System. text. encoding. ASCII. getBytes (data. toCharArray (); netSream. write (byData, 0, byData. length ); String emailData = string. Empty; string szTemp = sr. ReadLine (); if (szTemp [0]! = '-') // If an error is returned, the server returns a string starting with "-" {while (szTemp! = ". ") {SzTemp = sr. readLine (); emailData + = szTemp;} Console. writeLine (emailData);} else {Console. writeLine (szTemp) ;}} catch (Exception ex) {Console. writeLine ("Get email failed ");}}

    

    Iii. Summary: Blog needs to be improved in many places. Most of them refer to other people's code. And other blog posts. And then together. I hope Boyou can learn more about this. Give your own opinions. 3KU.

Code Link: http://files.cnblogs.com/FourLeafCloverZc/SpongeBob.Email.Learn.zip

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.