這裏演示若是把 Email provider 的資料寫在 WebConfig 裏和調用它. html
若是整個項目只須要使用一個 Email, 能夠寫入system.net裏, 微軟已經幫咱們設計好了web
<configuration> <system.net> <mailSettings> <smtp deliveryMethod="Network" from="Stooges Web Design Default <stooges@stooges.com.my>"> <network host="mail.stooges.com.my" port="587" userName="stooges@stooges.com.my" password="password" enableSsl="false" /> </smtp> </mailSettings> </system.net> <configuration>
而後簡單調用就能夠了ide
SmtpClient smtp = new SmtpClient(); MailMessage mail = new MailMessage { Subject = "subject", Body = "html content", IsBodyHtml = true }; mail.To.Add("hengkeat87@gmail.com"); smtp.Send(mail);
若是有多個Email要使用,咱們就得本身寫webconfig而後掉用了 : spa
讀 webconfig 資料能夠參考: http://www.cnblogs.com/keatkeat/p/5404128.html.net
<configuration> <configSections> <sectionGroup name="mailSettings"> <section name="stooges" type="System.Net.Configuration.SmtpSection"/> </sectionGroup> </configSections> <mailSettings> <stooges deliveryMethod="Network" from="Stooges Web Design<stooges@stooges.com.my>"> <network host="mail.stooges.com.my" port="587" userName="stooges@stooges.com.my" password="password" enableSsl="false" /> </stooges> </mailSettings> </configuration> SmtpClient smtp = new SmtpClient(); SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("mailSettings/stooges"); SmtpNetworkElement network = smtpSection.Network; smtp.Host = network.Host; smtp.Port = network.Port; smtp.EnableSsl = network.EnableSsl; smtp.UseDefaultCredentials = network.DefaultCredentials; smtp.Credentials = new NetworkCredential(network.UserName, network.Password); string from = smtpSection.From; //Stooges Web Design<stooges@stooges.com.my> int ipos = from.IndexOf("<"); string displayName = from.Substring(0, ipos); string email = from.Substring(ipos + 1, from.Length - displayName.Length - 2); MailMessage mail = new MailMessage { From = new MailAddress(email, displayName), Subject = "subject", Body = "html content", IsBodyHtml = true }; mail.To.Add("hengkeat87@gmail.com"); smtp.Send(mail);