Email地址有效性驗證

- 中國WEB開發者網絡 (http://www.webasp.net)
-- 技術教程 (http://www.webasp.net/article/)
--- Email地址有效性驗證 (http://www.webasp.net/article/15/14440.htm)
-- 作者:未知
-- 發佈日期: 2004-11-02
Email地址有效性的檢驗是一個經常遇到的問題啦!一般的檢驗方法是對Email地址字符串進行簡單的檢驗,如是否含有@ .等有效字符等。這種方法只能保證該地址從格式上看似有效,並不能保證地址可達。最近進行大量的地址校驗,寫了一個小程序,可以保證Email地址真正可達。


public bool checkEmail(string mailAddress)
{
TcpClient tcpc=new TcpClient();
try{
string server=mailAddress.Split('@')[1];
tcpc.Connect(server,25);
NetworkStream s=tcpc.GetStream();
StreamReader sr=new StreamReader(s,Encoding.Default);
string strR="";
strR=sr.ReadLine();
if(!strR.StartsWith("220")) return false;
StreamWriter sw=new StreamWriter(s,Encoding.Default);
sw.WriteLine("HELO");
sw.Flush();
strR=sr.ReadLine();
if(!strR.StartsWith("250")) return false;

sw.WriteLine("MAIL FROM;brookes@tsinghua.org.cn");
sw.Flush();
strR=sr.ReadLine();
if(!strR.StartsWith("250")) return false;

sw.WriteLine("RCPT TO:"+mailAddress);
sw.Flush();
strR=sr.ReadLine();
if(!strR.StartsWith("250")) return false;

sw.WriteLine("QUIT");
sw.Flush();
strR=sr.ReadLine();
return true;

}catch(Exception ee)
{
return false;
}
}


這個程序是根據SMTP的基本過程實現的。與一個mail服務器連接發郵件的基本過程可能是這樣的:

telnet mail.brookes.com 25
>>220 brookes.com<IMail 8.02>
HELO
>>250 mail.brookes.com
MAIL FROM:brookes@tsinghua.org.cn
>>250 Ok
RCPT TO:me@brookes.com
>>250 ok its for me@brookes.com
DATA
>>ok.send it ;end with <CRLF>.<CRLF>
soem data.
>>250 message queued
QUIT
>>221 Goodbye.



webasp.net