轉自:http://hi.baidu.com/bluesky_cn/item/8bb060ace834c53f020a4df2html
下面用到的郵件帳號和密碼都不是真實的,須要測試就換成本身的郵件帳號。服務器
須要引用:網絡
1 using System.Net.Mail; 2 using System.Text; 3 using System.Net;
程序代碼:測試
1 MailMessage myMail = new MailMessage(); //建立郵件實例對象 2 myMail.From = new MailAddress(""); //發送者,要和郵件服務器的驗證信息對應,不能隨便更改 3 4 myMail.To.Add(new MailAddress("")); //接收者 5 myMail.Subject = "C#發送Email"; //郵件標題 6 myMail.SubjectEncoding = Encoding.UTF8; //標題編碼 7 myMail.Body = "this is a test email!"; //郵件內容 8 myMail.BodyEncoding = Encoding.UTF8; //郵件內容編碼 9 myMail.IsBodyHtml = true; //郵件內容是否支持html 10 SmtpClient smtp = new SmtpClient(); //建立smtp實例對象 11 smtp.Host = "mail.sina.com"; //郵件服務器SMTP 12 smtp.Port = 25; //郵件服務器端口 13 smtp.Credentials = new NetworkCredential("", "123456"); //郵件服務器驗證信息 14 smtp.Send(myMail); //發送郵件
使用Gmail郵箱發送郵件示例this
1 MailMessage myMail = new MailMessage(); 2 myMail.From = new MailAddress(""); 3 myMail.To.Add(new MailAddress("")); 4 myMail.Subject = "C#發送Email"; 5 myMail.SubjectEncoding = Encoding.UTF8; 6 myMail.Body = "this is a test email from gmail!<a href='http://www.sina.com.cn'>sina</a>"; 7 myMail.BodyEncoding = Encoding.UTF8; 8 myMail.IsBodyHtml = true; 9 SmtpClient smtp = new SmtpClient(); 10 smtp.Host = "smtp.gmail.com"; 11 smtp.Port = 587; //Gmail的smtp端口 12 smtp.Credentials = new NetworkCredential("", "123456"); 13 smtp.EnableSsl = true; //Gmail要求SSL鏈接 14 smtp.DeliveryMethod = SmtpDeliveryMethod.Network; //Gmail的發送方式是經過網絡的方式,須要指定 15 smtp.Send(myMail);
使用QQ郵箱發送郵件示例編碼
1 MailMessage myMail = new MailMessage(); 2 myMail.From = new MailAddress(""); 3 myMail.To.Add(new MailAddress("")); 4 myMail.Subject = "C#發送Email"; 5 myMail.SubjectEncoding = Encoding.UTF8; 6 myMail.Body = "this is a test email from QQ!"; 7 myMail.BodyEncoding = Encoding.UTF8; 8 myMail.IsBodyHtml = true; 9 SmtpClient smtp = new SmtpClient(); 10 smtp.Host = "smtp.qq.com"; 11 smtp.Credentials = new NetworkCredential("", "123456"); 12 smtp.Send(myMail);