开发者

Can I check if an email address exists using .net?

开发者 https://www.devze.com 2023-01-19 06:36 出处:网络
Ive seen some php examples of how you can ping an inbox(wi开发者_开发问答thout sending any mail to it) to check whether it exists. I was wondering if anyone knows if this is possible with .net? If it

Ive seen some php examples of how you can ping an inbox(wi开发者_开发问答thout sending any mail to it) to check whether it exists. I was wondering if anyone knows if this is possible with .net? If it is Im going to write an app to do a bulk check on list of emails i have captured through my site.


SMTP defines the VRFY command for this, but since abuse by spammers totally overwhelmed the number of legitimate uses, virtually every e-mail server in the world is configured to lie.


What you mean about if you writing "check email"? Without sending some unique link for email owner you can't check this, you can only check syntax of email, and connection to smtp.

public static bool isEmail(string inputEmail)
{
   inputEmail  = NulltoString(inputEmail);
   string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
         @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
         @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
   Regex re = new Regex(strRegex);
   if (re.IsMatch(inputEmail))
    return (true);
   else
    return (false);
}

smtp check

string[] host = (address.Split('@'));
string hostname = host[1];

IPHostEntry IPhst = Dns.Resolve(hostname);
IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
Socket s= new Socket(endPt.AddressFamily, 
        SocketType.Stream,ProtocolType.Tcp);
s.Connect(endPt);


No, it is impossible in principle to check if an email exists - independent of language. There is simply no protocol to do it.

There are some partial solutions, but none of them are reliable.

See How to check if an email address exists without sending an email? for details.


​ 1. Get the MX record for the email provider by using following command:

nslookup -type=mx gmail.com
  1. Make call to tcp client to check if email is valid:

    private static void Main(string[] args)
    {            
      var gMail = IsEmailAccountValid("gmail-smtp-in.l.google.com", "aa.aa@gmail.com");
      Console.WriteLine($"Gmail account is valid - {gMail.ToString()}");
    
      var live = IsEmailAccountValid("live-com.olc.protection.outlook.com", "aa.aa@live.com");
      Console.WriteLine($"Live account is valid - {live.ToString()}");
    }
    
    private static byte[] BytesFromString(string str)
    {
      return Encoding.ASCII.GetBytes(str);
    }
    
    private static int GetResponseCode(string ResponseString)
    {
      return int.Parse(ResponseString.Substring(0, 3));
    }
    
    private static bool IsEmailAccountValid(string tcpClient, string emailAddress)
    {
      TcpClient tClient = new TcpClient(tcpClient, 25);
      string CRLF = "\r\n";
      byte[] dataBuffer;
      string ResponseString;
      NetworkStream netStream = tClient.GetStream();
      StreamReader reader = new StreamReader(netStream);
      ResponseString = reader.ReadLine();
    
      /* Perform HELO to SMTP Server and get Response */
      dataBuffer = BytesFromString("HELO Hi" + CRLF);
      netStream.Write(dataBuffer, 0, dataBuffer.Length);
      ResponseString = reader.ReadLine();
      dataBuffer = BytesFromString("MAIL FROM:<YourGmailIDHere@gmail.com>" + CRLF);
      netStream.Write(dataBuffer, 0, dataBuffer.Length);
      ResponseString = reader.ReadLine();
    
      /* Read Response of the RCPT TO Message to know from google if it exist or not */
      dataBuffer = BytesFromString($"RCPT TO:<{emailAddress}>" + CRLF);
      netStream.Write(dataBuffer, 0, dataBuffer.Length);
      ResponseString = reader.ReadLine();
      var responseCode = GetResponseCode(ResponseString);
    
      if (responseCode == 550)
      {
        return false;
      }
    
      /* QUITE CONNECTION */
      dataBuffer = BytesFromString("QUITE" + CRLF);
      netStream.Write(dataBuffer, 0, dataBuffer.Length);
      tClient.Close();
      return true;
    }
    

The MX record can be obtained using code:

var lookup = new LookupClient();
var result = lookup.QueryAsync("gmail.com", QueryType.ANY).Result;
var domainName = result.Additionals[result.Additionals.Count - 1].DomainName.Value;

Using above code find the MX lookup and use that MX lookup to check if email is valid or not.


http://www.codicode.com/art/free_asp_net_email_validator_verifier.aspx. Use the dll reference to your code. It is free both for personal use and redistribution. It checks for the domain name existence without actually sending an email.


This is not foolproof. The best you can do is check syntax and see if the domain name resolves.

Email syntax RegEx: (?<username>#?[_a-zA-Z0-9-+]+(\.[_a-zA-Z0-9-+]+)*)@(?<domain>[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|arpa|asia|coop|info|jobs|mobi|museum|name|travel)))


protected bool checkDNS(string host, string recType = "MX")
{
    bool result = false;
    try
    {
        using (Process proc = new Process())
        {
            proc.StartInfo.FileName = "nslookup";
            proc.StartInfo.Arguments = string.Format("-type={0} {1}", recType, host);
            proc.StartInfo.CreateNoWindow = true;
            proc.StartInfo.ErrorDialog = false;
            proc.StartInfo.RedirectStandardError = true;
            proc.StartInfo.RedirectStandardOutput = true;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            proc.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
                {
                    if ((e.Data != null) && (!result))
                        result = e.Data.StartsWith(host);
                };
            proc.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
                {
                    if (e.Data != null)
                    {
                        //read error output here, not sure what for?
                    }
                };
            proc.Start();
            proc.BeginErrorReadLine();
            proc.BeginOutputReadLine();
            proc.WaitForExit(30000); //timeout after 30 seconds.
        }
    }
    catch
    {
        result = false;
    }
    return result;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消