C # Network programming based SMTP sending e-mail

Source: Internet
Author: User
Tags imap mailmessage smtpclient

This paper mainly describes the programming of sending mail based on C # network programming, the mail sending function is based on the Mail protocol, the common e-mail protocol has SMTP (Simple Mail Transfer Protocol), POP3 (Post Office Protocol), IMAP (Internet Mail Access Protocol), the article mainly refers to the Zhou Cunjie of the C # Network Programming Example Tutorial. This is also the last Web-based programming article to take a look at the book, after which the series of articles are on the basis of the actual application of the network, no more on the principle of knowledge.

I. SMTP protocolThe SMTP protocol is the standard for inter-machine exchange of messages defined by the TCP/IP protocol family, and it is primarily responsible for how the underlying messaging system transmits a message from one machine to another, regardless of how fast the message is stored and transmitted. Its steps are basic such as the following:
The client first establishes a connection with the SERVERTCP, then the server sends a 220 message (service ready), the client sends a Hello command after receiving 220 messages, and the server responds with a hello. Finally, server and client can start mail communication.
This article does not prepare a descriptive description of the SMTP command (which defines the message transfer or user-defined system functionality) and the SMTP response status code, and you only need to know that the operation to send mail using SMTP is typically the following:
1. The Mail command (used to send the message to a multiple mailbox) starts with the sender's identity, and the RCPT command (used to determine the recipient of the message content) gives the recipient information.
2. List the contents of the sent message by using the data command (for message content to increase the buffer,<crlf>.<crlf> identity end).
3. The message content indicator confirms the operation, assuming that the command is accepted and the receiver returns an OK response.
       
. The SmtpMail class on the net platform implements the encapsulation of the SMTP protocol. So I mainly use these classes to describe how to send and receive SMTP mail.
Pop3:post Office Protocol, the current version number is POP3, which is the protocol that transfers messages from an e-mail address to the local computer.
Imap:internet message Access Protocol, an alternative protocol for POP3, provides a new feature for message retrieval and message processing that allows users to see the header summary of a message without having to download the message body. From the mail client software, you can manipulate the mail and folder folders on the server.
two. SMTP protocol encapsulated classes (Legacy) 1. smtpmail class
This class is used to send messages with a namespace of System.Web.Mail. This class often uses attributes with only one:
        Public static string SmtpServer {get; set;}
Gets or sets the SmtpServer name, if not set, that will use the local hostname. Assuming the hint to join the namespace does not exist, you need to add a reference to the project and add the System.Web.dll.
SMTP class frequent usage//construction method public smtpmail ();//send () method Send message return value: No public static void send (    mailmessage message//message);p ublic static void Send (    string from,        //Sender address string    to,/          /recipient address    String subject,     //message subject    string MessageText  //email content);

2.MailMessage class
its named control is System.Web.Mail, which is used to set the message content and information related to the content of the message, such as the sender's address, the recipient's address, and so on.

//mailmessage often use attributes The 1.Attachments property is used to get the file list of attachments public IList Attachments {get;} The 2.BCC property is used to get or set the address of the dark sent address, the public string Bcc {get; set;} The 3.Body property is used to get or set the message content public string Body {get; set;} The 4.BodyFormat property is used to get or set the format of the message content in HTML text format public MailFormat BodyFormat {get; set;} The 5.Cc property is used to get or set the address of CC to address, public string cc {get; set;} The 6.From property is used to get or set the address of the sender to public string from {get; set;} The 7.Headers property is used to get the message header public IDictionary Headers {get;} The 8.Priority property is used to get or set the priority of the message, which contains the high low normalpublic mailpriority precedence {get; set;} The 9.Subject property is used to get or set the subject of the message public string Subject {get; set;} The 10.To property is used to get or set the message's recipient address, public, string to {get; set;} Construction method Public MailMessage (); 

3.MailAttachment class
This class is used to construct and set attachments for messages with a namespace of System.Web.Mail.

The MailAttachment class often uses the attribute//encoding property to set the encoding of the attachment public mailencoding Encoding {get;} The FileName property is used to set the file name of the attachment to public string Filename {get;} Construction method Public MailAttachment (    string filename        //file name);p ublic mailattachment (    string filename,       // File name    mailencoding encoding  //code);
three. SMTP protocol encapsulated classes (new version)         Using older versions of SMTP can cause a lot of errors, such as "Invalid sendusing configuration value" or "Server not responding", but it has basically no transformations with the new methods and properties.
The smtp namespace for C # updates is System.Net.Mail, where the SmtpClient class is used for SMTP sending messages.
The 1.Host property is used to set the host name or IP address
The 2.Port property is used to set the SMTP transaction port
The 3.Credentials attribute is used to verify the sender's authentication
The 4.DeliveryMethod attribute is used to specify how to handle the e-mail message to be sent
The 5.Send method is used to send e-mail messages to the SMTP server for delivery
The properties in the MailMessage class also change, such as the To attribute (message recipient address attribute) to a read-only attribute that needs to be added to the recipient's email address via the Add function, but roughly the same as the old version.
The attachment class is added in System.Net.Mail, which represents an attachment to an e-mail message that was once System.Web.Mail in the MailAttachment class. The following is a detailed example of sending a message source and effect:

Join the namespace using system.net.mail;//to join the private mailmessage msg;       Used to construct message properties and methods Private Attachment att;    Used to construct message attachment properties and Methods public Form1 () {InitializeComponent ();  msg = new MailMessage ();        Instantiate}//click the "Send Mail" button private void Button1_Click (object sender, EventArgs e) {try {//to Mail Recipient address attribute only read-only attribute cannot be assigned value Msg.        To.add (TextBox1.Text); The From Message Sender address attribute msg.        from = new MailAddress (TextBox2.Text); Subject message subject attribute MSG.        Subject = TextBox3.Text; Msg.        subjectencoding = Encoding.default; Body sets the message Content property MSG.        Body = richTextBox1.Text; Msg.        bodyencoding = Encoding.default; Sets the priority attribute of the message to the 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 mail SmtpClient client = new SmtpClient (); Mail server settings smtpport default to client.                   Host = "smtp.163.com"; Client.                               Port = 25; The message is sent over the network to the SmtpServer client.        Deliverymethod = System.Net.Mail.SmtpDeliveryMethod.Network; The username and password client of the credential sender's logon mailbox.        Credentials = new System.Net.NetworkCredential ("1520161xxxx", "19911203xxxx"); Client.        Send (msg); MessageBox.Show ("Mail sent successfully!      "," hint ", MessageBoxButtons.OK, MessageBoxIcon.Information);    } catch (Exception m)//exception handling {MessageBox.Show (m.message); }}//Click "Add Attachment" button private void button2_click (object sender, EventArgs e) {OpenFileDialog OpenFileDialog = new Openfiledialo    g ();  Openfiledialog.checkfileexists = true;    File name not present warning Openfiledialog.validatenames = true;     The value accepts Win32 file Openfiledialog.multiselect = false;                Do not agree to multi-select File Openfiledialog.filter = "All Files (*. *) |*.*"; Adding an attachment now only supports adding an attachment 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 ();}

The result of the execution is, for example, seen:


This is not the basic knowledge that C # uses SMTP to send mail, and readers can make better interfaces themselves.

Four. Summary

You can also invoke the Windows-delivered mail sender Implementation, Windows comes with Outlook Express software that can call Outlook Express via function ShellExecute () or CreateProcess (), Ctrl+r call "Execute" and enter "Mailto:[email protected]" to send the message. The first Test account is required to use the software, and I am bound to 163 mailboxes. The reader is interested in being able to complete himself.
This article mainly describes the C # network programming in the SMTP mail protocol, how to send the message process, and compared to the new version and the old method. This will be my last article in C # Network programming, and Next I want to learn C # network programming crawler, download mesh, Data mining combined with such knowledge. Hope the article is helpful to everyone, if there are errors or shortcomings, please Haihan! Now France vs Swiss 3:0.
(By:eastmount 2014-6-21 Night 4 points original csdn http://blog.csdn.net/eastmount/ )
         refer to the related information, very good, worth learning:
1.[c# Network Programming Series] Topic Ten: Implementing a Simple Mail transceiver--Learning_hard

        http://blog.csdn.net/learning_hard/article/details/9071041
2.c# using 163 smtpserver to send mail--Powercoder
http://www.cnblogs.com/OpenCoder/archive/2010/07/16/1779247.html
3.c# Mail Download--Zhouquanandy
http://download.csdn.net/detail/zhouquanandy/4444802
4. "C # Network Programming Example Tutorial"--Zhou Cunjie
5.c# Send mail (add attachment)--look forward to autumn leaves
http://blog.csdn.net/kkkkkxiaofei/article/details/7941239

C # Network programming based SMTP sending e-mail

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.