一個國外的英文網站上有非常詳細的代碼說明:
相關的資料地址:http://www.systemnetmail.com/
下面的代碼是我參考資料寫出的一個樣本:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Net.Mail;
namespace Email_Test.aspx
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string emailTitle = "測試email";
string toEmail = "seagreen7@yeah.net";
string mycontent = "這是測試郵件內容";
string myResult = SendHtmlEmail(emailTitle, toEmail, mycontent);
if (myResult == "ok")
{ this.Label1.Text = "恭喜,郵件已經成功發送給" + toEmail; }
else
{ this.Label1.Text = "抱歉,郵件發送失敗,請檢查web.config檔案的配置資訊 system.net 節點。" ; }
}
public static string SendHtmlEmail(string EmailTitle, string destEmail, string EmailContent)
{
try
{
// 讀取web.config中的郵件發送的配置資訊
//在這裡的代碼中,我們不需要設定SmtpClient類的任何屬性,因為它們已經在Web.config檔案中指定了
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.To.Add(destEmail);
//set the content
mail.Subject = EmailTitle;
//screen scrape the html
string html = EmailContent;
mail.Body = html;
mail.IsBodyHtml = true;
//send the message
SmtpClient smtp = new SmtpClient();
smtp.Send(mail);
}
catch (Exception e)
{
return "fail<br>" + e.ToString(); //發送失敗,返回fail
}
return "ok"; //發送成功,返回 ok
}
}
}
web.config的內容如下:
<system.net>
<mailSettings>
<!-- 發送郵件設定,把這裡的郵箱地址和密碼設定成你自己的就ok了 -->
<smtp from="yours@126.com">
<network host="smtp.126.com" port="25" userName="yours@126.com" password="123456" defaultCredentials="false"/>
</smtp>
</mailSettings>
</system.net>