System.Net.Mail是微軟自家提供的工具,在.net程序中能夠使用該空間中的SmtpClient實例來實現郵件的發送。html
使用System.Net.Mail空間與Web.config配置相配合,能夠很方便的實現郵件發送。服務器
首先,在Web.config文件中<system.net>節點中加入<mailSettings>標籤,示例以下:app
<system.net>
<mailSettings>
<smtp from="測試者<tester@testserver.com>">
<network host="smtp.ym.163.com" password="MyTestPassword" port="25"
userName="tester@testserver.com" enableSsl="false" defaultCredentials="false" />
</smtp>
</mailSettings>
</system.net>
接下來即是C#代碼:(須要using System.Net.Mail;)工具
/// <summary>
/// 發送HTML郵件,有抄送和密送
/// 須要在Web.config文件中的system.net下的mailSettings節點進行配置
/// </summary>
/// <param name="mailto">收件人地址</param>
/// <param name="mailcc">抄送地址</param>
/// <param name="mailbcc">密送地址</param>
/// <param name="mailsubject">郵件主題</param>
/// <param name="mailbody">郵件正文</param>
public static void SendMail(string mailto, string mailcc, string mailbcc, string mailsubject, string mailbody)
{
MailMessage mMessage = new MailMessage();
MailAddress mTo = new MailAddress(mailto);
if (mailcc != "") { MailAddress mCC = new MailAddress(mailcc); mMessage.CC.Add(mCC); }
if (mailbcc != "") { MailAddress mBCC = new MailAddress(mailbcc); mMessage.Bcc.Add(mBCC); }
mMessage.To.Add(mTo);
mMessage.Subject = mailsubject;
//正文和主題的字符編碼都設置爲UTF8
mMessage.SubjectEncoding = System.Text.Encoding.UTF8;
mMessage.BodyEncoding = System.Text.Encoding.UTF8;
mMessage.Body = mailbody;
//正文支持html
mMessage.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Send(mMessage);
}
再接下來就能夠在程序任意位置調用SendMail方法來實現發送郵件了:測試
SendMail("272023290@qq.com", "", "", "測試20140418-2", "<h1>你好,這是第二封測試郵件</h1>");
若是程序所使用的SMTP服務器不做特殊限制的話,你的收件箱就能夠正常收到這封測試郵件了。編碼
同時,因爲咱們在Web.config中設置的是「郵件測試者<tester@testserver.com>」,因此收到的郵件的發件人將會是「郵件測試者」。spa
本文結束。.net