First, import the namespace:
The code is as follows: |
Copy code |
Using System. Net. Mail; |
Define the method for sending emails. [there are many differences on the internet. For more information, see WinForm.]
The code is as follows: |
Copy code |
/// <Summary> /// Send an email /// </Summary> /// <Param name = "MessageFrom"> sender's email address </param> /// <Param name = "MessageTo"> recipient's email address </param> /// <Param name = "MessageSubject"> subject </param> /// <Param name = "MessageBody"> email content </param> /// <Returns> </returns> Public bool Send (MailAddress MessageFrom, string MessageTo, string MessageSubject, string MessageBody) { MailMessage message = new MailMessage (); Message. From = MessageFrom; Message. To. Add (MessageTo); // you can specify multiple recipient email addresses for group sending. Message. Subject = MessageSubject; Message. Body = MessageBody; Message. IsBodyHtml = true; // whether it is in html format Message. Priority = MailPriority. Normal; // mail Priority SmtpClient SC = new SmtpClient (); SC. Host = "smtp.qq.com"; // specify the server address or IP address of the email. SC. Port = 25; // specify the sending Port // Specify the username and password for logging on to the server (sender's email login password) SC. Credentials = new System. Net. NetworkCredential ("[sending address]", "[sending password ]"); Try { SC. Send (message); // Send an email } Catch { Return false; } Return true; } |
How to send an email
Call the defined method to send emails:
The code is as follows: |
Copy code |
/// <Summary> /// Send an email /// </Summary> /// <Param name = "sender"> </param> /// <Param name = "e"> </param> Protected void ForMail (string name, string mail) { Try { // String email = txtemail. Text. Trim (); MailAddress MessageFrom = new MailAddress ("[sender address]"); // sender's email address String MessageTo = mail; // recipient's email address String MessageSubject = bs. HtmlEncode (subject ); // Mail content (generally a URL link that generates a random number and adds the verification id parameter. Click go to website verification .) "; String MessageBody = "" + content1.Value. Trim () + ""; If (Send (MessageFrom, MessageTo, MessageSubject, MessageBody )) { // Response. Write ("email sent successfully "); } Else { // Response. Write ("failed to send mail "); } } Catch { // ClientScript. RegisterStartupScript (ClientScript. GetType (), "myscript", "<script> alert ('Client information deletion failed') </script> "); } }
|
Call method to send an email
Smtp addresses in different mailboxes are different. For example, smtp.qq.com for QQ and smtp.163.com for 163