Introduce namespace
Using System. Net. Mail;
Using System. Net;
Private static bool SendMail (string toAddress, string mailSubject, string mailBody)
{
MailAddress from = new MailAddress ("xiachufeng@126.com", "xiachufeng"); // set the sender mailbox and display name
MailAddress to = new MailAddress (toAddress, "gangge"); // set the recipient's mailbox and display name
MailMessage oMail = new MailMessage (from, to); // create a MailMessage object
OMail. Subject = mailSubject; // mail title
OMail. Body = mailBody; // mail content
OMail. Attachments. Add (new Attachment ("D: \ project.rar"); // Attachment
OMail. IsBodyHtml = true; // specifies the mail format. The HTML format is supported.
OMail. BodyEncoding = System. Text. Encoding. GetEncoding ("UTF-8"); // The Encoding used by the email
OMail. Priority = MailPriority. High; // set the Priority of the email to High.
// Sending email server
SmtpClient client = new SmtpClient ();
Client. Host = "smtp.126.com"; // specify the email server
Client. Credentials = new NetworkCredential ("xiachufeng@126.com", "your password"); // specify the server email and password
Try
{
Client. Send (oMail); // Send an email
}
Catch (Exception eall)
{
String str = eall. Message;
Return false;
}
Finally
{
OMail. Attachments. Dispose ();
OMail. Dispose (); // release resources
}
Return true;
}
/// <Summary>
/// Call to send an email
/// </Summary>
/// <Param name = "sender"> </param>
/// <Param name = "e"> </param>
Protected void button#click (object sender, EventArgs e)
{
Bool B = SendMail ("duchenggang.accp@163.com", "hello", "Haha, do a test gang ");
If (B = true)
{
ClientScript. RegisterStartupScript (this. GetType (), "onclick", "<script> alert ('OK') </script> ");
}
Else
{
ClientScript. RegisterStartupScript (this. GetType (), "onclick", "<script> alert ('error') </script> ");
}
}