C# 如何验证邮件地址
getMailServer(string strEmail),传入邮件地址
如果返回null,说明邮件地址无效;
如果返回有字符,例如:传入参数
kimi@163.com 方法执行后,返回163mx03.mxmail.netease.com
说明邮件地址中可以解析出一个邮件服务器地址
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.IO;
using System.IO;
//检查邮件服务器,如果mail exchanger不为null,返回mail server地址
public string getMailServer(string strEmail)
{
if (!IsEmail(strEmail))
public string getMailServer(string strEmail)
{
if (!IsEmail(strEmail))
{
return null;
}
string strDomain = strEmail.Trim().ToLower().Split( '@')[1];
ProcessStartInfo PSinfo = new ProcessStartInfo();
PSinfo.UseShellExecute = false;
PSinfo.RedirectStandardInput = true;
PSinfo.RedirectStandardOutput = true;
PSinfo.FileName = "nslookup";
PSinfo.CreateNoWindow = true;
PSinfo.Arguments = "-type=mx " + strDomain;
Process proc = Process.Start(PSinfo);
StreamReader Sreader = proc.StandardOutput;
Regex rgx = new Regex("mail exchanger = (?<mailServer>[^//s]+)");
string strResponse = "";
while ((strResponse = Sreader.ReadLine()) != null)
{
Match aMatch = rgx.Match(strResponse);
if (rgx.Match(strResponse).Success)
{
string Gvalue = aMatch.Groups["mailServer"].Value;
return Gvalue;
}
}
return null;
}
return null;
}
string strDomain = strEmail.Trim().ToLower().Split( '@')[1];
ProcessStartInfo PSinfo = new ProcessStartInfo();
PSinfo.UseShellExecute = false;
PSinfo.RedirectStandardInput = true;
PSinfo.RedirectStandardOutput = true;
PSinfo.FileName = "nslookup";
PSinfo.CreateNoWindow = true;
PSinfo.Arguments = "-type=mx " + strDomain;
Process proc = Process.Start(PSinfo);
StreamReader Sreader = proc.StandardOutput;
Regex rgx = new Regex("mail exchanger = (?<mailServer>[^//s]+)");
string strResponse = "";
while ((strResponse = Sreader.ReadLine()) != null)
{
Match aMatch = rgx.Match(strResponse);
if (rgx.Match(strResponse).Success)
{
string Gvalue = aMatch.Groups["mailServer"].Value;
return Gvalue;
}
}
return null;
}
//正则表达式验证Email地址格式
public bool IsEmail(string str_Email)
{
return Regex.IsMatch(str_Email, @"^([/w-/.]+)+[a-zA-Z0-9]+@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)$");
}
public bool IsEmail(string str_Email)
{
return Regex.IsMatch(str_Email, @"^([/w-/.]+)+[a-zA-Z0-9]+@((/[[0-9]{1,3}/.[0-9]{1,3}/.[0-9]{1,3}/.)|(([/w-]+/.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(/]?)$");
}