This article mainly describes the programming of sending mail based on C # network programming. The mail sending function is based on the mail protocol. Common e-mail protocols include SMTP (Simple Mail Transfer Protocol) POP3 (Post Office Protocol), IMAP (Internet Mail Access Protocol), the article mainly refer to Zhou cunjie's "C # network programming example tutorial". this is also the last article referring to the book's network programming. later articles in this series are based on the actual application of the network and will not talk about the principles in large quantities.
I. SMTP protocol
SMTP is the standard for inter-machine mail exchange defined by the TCP/IP protocol family. It is mainly responsible for how the underlying Mail System transfers a message from one machine to another, it does not care about how emails are stored and the transmission speed. the procedure is as follows:
The client first establishes a TCP connection with the server, and then the server sends 220 packets (the service is ready). After the client receives 220 packets, it sends the HELLO command, and the server responds after receiving the HELLO message, finally, the server and client can start email communication.
This document does not describe the SMTP command (which defines mail transmission or user-defined system functions) and SMTP response status code, you only need to know that the procedure for sending mail via SMTP is usually as follows:
1. The sender ID is provided by the MAIL command (used to send an email to multiple mailboxes), and the RCPT command (used to determine the recipient of the email content) gives the recipient information.
2. Use the DATA command (used to add the mail content to the buffer, and the <CRLF>. <CRLF> flag ends) to list the content of the sent mail.
3. The mail content indicator confirms the operation. If this command is accepted, the recipient returns a 250 OK response.
On the. NET platform, the SmtpMail class encapsulates the SMTP protocol. Therefore, I mainly use these classes to introduce how to send and receive SMTP mail.
POP3: Post Office Protocol. The current version is POP3. It is a Protocol used to transfer emails from an email to a local computer.
IMAP: Internet Message Access Protocol, an alternative Protocol for POP3, provides new features for mail retrieval and mail processing. You can view the Title Summary of a mail without having to download the body of the mail, the mail client can operate the mail and folder directories on the server.Ii. SMTP encapsulation class (Old Version)
1.
SmtpMail class
This class is used to send emails. Its namespace is System. Web. Mail. This class has only one common attribute:
Public static string SmtpServer {get; set ;}
Obtain or set the SMTP server name. If this parameter is not set, the local host name will be used. If you are prompted that the namespace does not exist, add reference to the project and add System. Web. dll.
// SMTP common method // constructor public SmtpMail (); // Send () method returns the mail: No public static void Send (MailMessage message // mail ); public static void Send (string from, // string to for the sender address, // string subject for the recipient address, // mail subject string messageText // mail content );
2. MailMessage class
Its naming control is System. Web. Mail, which is used to set the Mail content and information related to the Mail content, such as the Mail address and recipient address.
// Common attributes of MailMessage // 1. the Attachments attribute is used to obtain the Object List of the attachment public IList Attachments {get;} // 2. the Bcc attribute is used to obtain or set the addresses that are implicitly sent to. The public string Bcc {get; set;} // 3. the Body attribute is used to obtain or set the public string Body {get; set;} // 4. the BodyFormat attribute is used to obtain or set the mail content in Html Text format public MailFormat BodyFormat {get; set;} // 5. the Cc attribute is used to obtain or set the Cc address. The Cc address is public string Cc {get; set;} // 6. the From attribute is used to obtain or set the sender's address public string From {get; set;} // 7. the Headers attribute is used to obtain the mail header public IDictionary Headers {get;} // 8. the Priority attribute is used to get or set the mail Priority, including High Low Normalpublic MailPriority Priority {get; set ;}// 9. the Subject attribute is used to obtain or set the Subject public string Subject {get; set;} // 10. the To attribute is used To obtain or set the email recipient's address public string To {get; set;} // constructor public MailMessage ();
3. MailAttachment class
This class is used to construct and set email attachments. The namespace is System. Web. Mail.
// Common attributes of the MailAttachment class // The Encoding attribute is used to set the attachment Encoding public MailEncoding Encoding {get ;}// the Filename attribute is used to set the attachment file name public string Filename {get ;} // constructor public MailAttachment (string filename // file name); public MailAttachment (string filename, // file name MailEncoding encoding // encoding );
Iii. SMTP protocol encapsulated classes (new version)
Using the old version of SMTP may cause many errors, such as "invalid SendUsing configuration value" or "server not responding", but it is basically not changed with the new version of methods and attributes.
C # The updated smtp namespace is System. Net. Mail. The SmtpClient class is used for smtp Mail sending.
1. The Host attribute is used to set the Host name or IP address.
2. The Port attribute is used to set the SMTP transaction Port.
3. The Credentials attribute is used to verify the sender's authentication.
4. The DeliveryMethod attribute is used to specify how mail messages to be sent are processed.
5. The Send method is used to Send emails to the SMTP server for transmission.
Attributes in the MailMessage class also change. For example, you need To use the Add function To Add the recipient email address if the To attribute (email recipient address attribute) is changed To the read-only attribute, but it is basically the same as that in the old version.
The Attachment class is in the System. net. added in Mail, indicating the attachment of the email. web. the MailAttachment class is in Mail. the following figure shows the source code and effects of the email sending instance:
// Add the namespace using System. net. mail; // Add private member private MailMessage msg; // used to construct Mail attributes and Methods private Attachment att; // used to construct Mail Attachment attributes and Methods public Form1 () {InitializeComponent (); msg = new MailMessage (); // instantiate} // click the "send email" button private void button#click (object sender, EventArgs e) {try {// To email recipient address attribute read-only attribute cannot be assigned msg. to. add (textBox1.Text); // From mail sender address attribute msg. from = new MailAddress (textBox2.Text); // Subject mail Subject attribute msg. subject = tex TBox3.Text; msg. subjectEncoding = Encoding. default; // set the message content attribute msg. body = richTextBox1.Text; msg. bodyEncoding = Encoding. default; // set the Priority of the email. Priority attribute if (radioButton1.Checked) msg. priority = MailPriority. high; else if (radioButton2.Checked) msg. priority = MailPriority. low; else if (radioButton3.Checked) msg. priority = MailPriority. normal; else msg. priority = MailPriority. normal; // send the SmtpCl email Ient client = new SmtpClient (); // The Mail Server sets the smtp port to 25 by default. host = "smtp.163.com"; client. port = 25; // send the email to the SMTP server client over the network. deliveryMethod = System. net. mail. smtpDeliveryMethod. network; // the user name and password of the sender's logon email address client. credentials = new System. net. networkCredential ("1520161 xxxx", "19911203 xxxx"); client. send (msg); MessageBox. show ("email sent successfully! "," Prompt ", MessageBoxButtons. OK, MessageBoxIcon. information);} catch (Exception m) // Exception Handling {MessageBox. show (m. message) ;}}// click the "add attachment" button private void button2_Click (object sender, EventArgs e) {OpenFileDialog openFileDialog = new OpenFileDialog (); openFileDialog. checkFileExists = true; // warning openFileDialog is displayed if the file name does not exist. validateNames = true; // The value accepts the openFileDialog of the Win32 file. multiselect = false; // you are not allowed to select multiple files in openFileDialog. filter = "all files (*. *) | *. * "; // only one attachment can be added if (openFileDialog. showDialog () = DialogResult. OK) {richTextBox1.Text = openFileDialog. fileName; att = new Attachment (openFileDialog. fileName); msg. attachments. add (att) ;}// click the "delete attachment" button private void button3_Click (object sender, EventArgs e) {msg. attachments. clear ();}
Shows the running result:
This is only the basic knowledge of C # sending mails using SMTP, and the readers can make a better interface by themselves.
Iv. Summary
You can also call the mail sending program that comes with Windows, and the Outlook Express software that comes with Windows. You can call Outlook Express by using the ShellExecute () or CreateProcess () function, Ctrl + R to call "run ", enter mailto: eastmount@163.com to call the send mail. when using this software, you must first test your account. I am bound to a 163 mailbox. you can do it yourself if you are interested.
This article describes how to send emails through the SMTP protocol in C # network programming, and compares the new and old methods. this will be my last article on C # network programming. Next I want to learn about C # web programming crawlers, download web clips, and combine data mining. I hope this article will help you. If you have any errors or deficiencies, please try again! Currently, France vs. Switzerland.
(By: Eastmount original CSDN http://blog.csdn.net/eastmount/)
The reference documents are recommended, which are very good and worth learning:
1. [C # network programming series] Topic 10: implement simple email transceiver-Learning_Hard
Http://blog.csdn.net/learning_hard/article/details/9071041
2. C # Use the 163 SMTP server to send an email -- PowerCoder
Http://www.cnblogs.com/OpenCoder/archive/2010/07/16/1779247.html
3. C # download email -- zhouquanandy
Http://download.csdn.net/detail/zhouquanandy/4444802
4. C # network programming example tutorial -- Zhou cunjie
5. C # send an email (add an attachment) -- ye expected to fall
Http://blog.csdn.net/kkkkkxiaofei/article/details/7941239