VS2005(asp.net2.0)輕鬆發送郵件。
在asp.net 2.0裡面可以很簡單地開發出來smtp寄送電子郵件。不像asp還得註冊jmail控制項什麼的。
需要引用下列命名空間:
using System.Net.Mail;
using System.Net;
下面是通過smtp.126.com發送郵件。smtp.126.com需要身分識別驗證。
protected void SendMail_Click(object sender, EventArgs e)
{
string to = "xpnew@126.com";
string from = "xpnew@126.com";
string subject = MailTitle.Text;// "Using the new SMTP client.";
string body = MailBody.Text;// @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("smtp.126.com", 25);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Credentials = new NetworkCredential("xpnew", "XXXXXX");//這裡是改成你自己的帳號和密碼
client.Send(message);
}
下面是通過本機(IIS內建的smtp伺服器)發送,沒有身分識別驗證。
這個其實也很有用,通常來說,實際工作當中會遇到開發企業內部的web應用程式(比如說OA),那麼就得使用內部的smtp伺服器了。
只可惜,搞了一下午也沒有通過測試。(不能中繼到internet)
protected void SendFromLocal_Click(object sender, EventArgs e)
{
string to = "xpnew@126.com";
string from = "xpnew@126.com";
string subject = MailTitle.Text;// "Using the new SMTP client.";
string body = MailBody.Text;// @"Using this new feature, you can send an e-mail message from an application very easily.";
MailMessage message = new MailMessage(from, to, subject, body);
SmtpClient client = new SmtpClient("localhost", 25);
// Credentials are necessary if the server requires the client
// to authenticate before it will send e-mail on the client's behalf.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
client.Send(message);
}
通過本機發送的時候,可能會出現一些問題。
1、"郵箱不可用。 伺服器響應為: 5.7.1 Unable to relay for xpnew@126.com"
解決辦法:
在IIS中,右擊“預設SMTP虛擬伺服器”,選擇“屬性”,切換到“訪問”頁,點擊“中繼”按鈕,在彈出框中選擇“僅以下列表除外”,確定。
2、郵件發送出去了,但是對方卻收不到。
原因暫時還沒有找到。在網上尋找了一些資料,好像是因為被對方的伺服器認定為垃圾郵件了。
參考資料:
1、MSDN:.NET Framework 類庫 SmtpClient.Credentials 屬性
2、vs2003 和vs2005下的發送SMTP郵件 (downmoon原創)
http://dev.21tx.com/2006/01/22/10217.html
3、出錯:5.7.1
http://blog.csdn.net/beimuaihui/archive/2007/08/12/1739409.aspx
4、在Win2003中為 Internet 資訊服務 SMTP 漏洞轉發匿名郵件伺服器配置遠端網域
http://www.knowsky.com/341533.html