Example tutorial for sending email in ASP. NET, asp.net instance tutorial
First, import the namespace:
Using System. Net. Mail;
Define the method for sending emails. [There are many differences on the Internet. For more information, see WinForm.]
/// <Summary> /// send an email /// </summary> /// <param name = "MessageFrom"> sender's email address </param> /// <param name = "MessageTo"> recipient's email address </param> /// <param name = "MessageSubject"> Email 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); // multiple recipient email addresses can be used to send Group messages. subject = MessageSubject; message. body = MessageBody; message. isBodyHtml = true; // whether the message is in html format. priority = MailPriority. normal; // the priority of the sent mail. SmtpClient SC = new SmtpClient (); SC. host = "smtp.qq.com"; // specify the server address or IP address of the email. port = 25; // specify the sending Port // specify the username and password of the login server (the sender's email login password) SC. credentials = new System. net. networkCredential ("[Sending address]", "[sending Password]"); try {SC. send (message); // Send the email} catch {return false;} return true ;}
How to send an email
Call the defined method to send Emails:
The Code is as follows:
/// <Summary> /// send the 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 (mail subject); // mail content (generally a URL link, generate a random number, add the verification id parameter, and click go to the website for verification .) "; String MessageBody =" "+ content1.Value. trim () + ""; if (Send (MessageFrom, MessageTo, MessageSubject, MessageBody) {// Response. write ("successfully sent");} else {// Response. write ("failed to send email");} catch {// ClientScript. registerStartupScript (ClientScript. getType (), "myscript", "<script> alert ('failed to delete customer information') </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