asp.net利用SmtpClient发送邮件
using System; using System.Data; using System.Web.UI; using System.Data.OracleClient; using DBUtility; using System.Text.RegularExpressions; using System.Net; using System.Net.Mail; using System.Xml; using System.Net.Mime; using System.Text; using System.Collections.Generic; public partial class Page_ForgetPass : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } //提交邮件 protected void btnMailSub_Click(object sender, EventArgs e) { //判断用户填入的邮箱地址是否在系统里面注册 if (1 > 2)//自行修改一下 { } else { string pass = GetPassByEmail(emailAdd);//通过邮件获取密码 //发送邮件修改密码 try { Dictionary<string, string> mailInfo = ReadXML();//读取配置文件,获取发送人、收件人信息 string fromEmailAdd = mailInfo["from"];//发件人邮箱地址。如:xxxlong@sina.com string fromalias = mailInfo["fromalias"];//发件人显示名字(别名,默认情况下显示发件人邮箱地址)。如:小龙,不写发件人则显示xxxlong@sina.com string fromEmailAddPass = mailInfo["frompass"];//发件人邮箱密码。如:123456——xxxlong@sina.com邮箱登陆密码 string toEmailAdd = emailAdd;//有坚韧邮箱地址。如:892764123@qq.com string subject = mailInfo["subject"];//邮件标题。如:发送邮件的标题 string body = mailInfo["body"];//邮件正文。如:发送邮件正文 string host = mailInfo["host"];//发送邮件服务器(smtp.加上服务器地址)。如sina.com.cn——新浪域名 MailAddress from = new MailAddress(fromEmailAdd);//发送邮件邮箱地址 MailAddress to = new MailAddress(toEmailAdd);//发送邮件邮箱密码 MailMessage message = new MailMessage(); message.To.Add(to); message.From = new MailAddress(fromEmailAdd, fromalias, Encoding.UTF8); string bb = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">"; bb += "<html>"; bb += "<head>"; bb += "<title></title>"; bb += "<style type=\"text/css\">"; //bb += "div{ width:100px; height:100px; background-color:Red;}"; bb += "</style>"; bb += "</head>"; bb += "<body>"; bb += "<div>"; bb += "尊敬的用户,您的密码是:" + pass + ",请妥善保管您的密码!【世友租车】"; bb += "</div>"; bb += "</body>"; bb += "</html>"; message.IsBodyHtml = true;//是否是html message.Priority = MailPriority.High;//优先级 message.Subject = subject;//发送邮件标题 message.SubjectEncoding = Encoding.UTF8;//标题编码 message.Body = bb; message.BodyEncoding = Encoding.UTF8;//正文编码 SmtpClient client = new SmtpClient(); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Port = 25; client.Host = "smtp." + host;//发送邮件服务器地址 client.Credentials = new System.Net.NetworkCredential(fromEmailAdd, fromEmailAddPass);//发送邮件邮箱地址和密码 client.Send(message); string mess = Server.UrlEncode("密码已发送到您指定的邮箱,请注意查收!"); Response.Redirect("BackPass.html?mess=" + mess); } catch (Exception ex) { } } } catch (Exception ex) { } } //读取配置文件,获取邮件发送服务器信息 private Dictionary<string, string> ReadXML() { Dictionary<string, string> hashMail = new Dictionary<string, string>(); try { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(Server.MapPath("xml/mail.xml"));//加载xml文件 XmlNode root = xmlDoc.SelectSingleNode("mailinfo");//获取根节点 //遍历所有节点,根节点除外。 //将所有的节点名字和内容以键值对的方式存储。 if (root.HasChildNodes) { foreach (XmlNode node in root.ChildNodes) { hashMail.Add(node.Name, node.InnerText); } } } catch (Exception ex) { } return hashMail; } }