C # Check the Email address validity by detecting the Email server

Source: Internet
Author: User
Tags nslookup

The verification of Email address validity is a common problem! The general check method is to perform a simple format check on the Email address string, such as whether it contains valid characters such. This method can only ensure that the address looks valid in the format, and cannot guarantee that the address can be reached. Recently, a large number of address verification tasks were carried out, and a small program was written to check whether the Email address is truly reachable.


The Email address consists of the user name and Email server. Therefore, the verification email address can be divided into two steps: first, check the email server and then check the user name. For example, the abc@163.com first checks whether the 163.com Server is a valid email server, and then checks whether there is an abc user on the server.

Query the DNS server and obtain the MX (Mail Exchanger) Record of the domain name to determine whether the email server corresponding to a domain name is valid. In Windows, you can use the nslookup program to view this record.

// Use the nslookup program to query MX records and obtain the mail server corresponding to the domain name

public string getMailServer (string strEmail)
        {
            string strDomain = strEmail.Split ('@') [1];
            ProcessStartInfo info = new ProcessStartInfo ();
            info.UseShellExecute = false;
            info.RedirectStandardInput = true;
            info.RedirectStandardOutput = true;
            info.FileName = "nslookup";
            info.CreateNoWindow = true;
            info.Arguments = "-type = mx" + strDomain;
            Process ns = Process.Start (info);
            StreamReader sout = ns.StandardOutput;
            Regex reg = new Regex ("mail exchanger = (? <MailServer> [^ \\ s]. *)");
            string strResponse = "";
            while ((strResponse = sout.ReadLine ())! = null)
            {
                Match amatch = reg.Match (strResponse);
                if (reg.Match (strResponse) .Success) return amatch.Groups ["mailServer"]. Value;
            }
            return null;
        }
 The second step is to connect to the mail server to confirm the availability of the server and whether the user exists

public int checkEmail (string mailAddress, out string errorInfo)
        {
            Regex reg = new Regex ("^ [a-zA-Z0-9 _-] + @ [a-zA-Z0-9 _-] + (\\. [A-zA-Z0-9 _-] +) + $" );
            if (! reg.IsMatch (mailAddress))
            {
                errorInfo = "Email Format error!";
                return 405;

            }
            string mailServer = getMailServer (mailAddress);
            if (mailServer == null)
            {
                errorInfo = "Email Server error!";
                return 404;
            }
            TcpClient tcpc = new TcpClient ();
            tcpc.NoDelay = true;
            tcpc.ReceiveTimeout = 3000;
            tcpc.SendTimeout = 3000;
            try
            {
                tcpc.Connect (mailServer, 25);
                NetworkStream s = tcpc.GetStream ();
                StreamReader sr = new StreamReader (s, Encoding.Default);
                StreamWriter sw = new StreamWriter (s, Encoding.Default);
                string strResponse = "";
                string strTestFrom = mailAddress;
                sw.WriteLine ("helo" + mailServer);
                sw.WriteLine ("mail from: <" + mailAddress + ">");
                sw.WriteLine ("rcpt to: <" + strTestFrom + ">");
                strResponse = sr.ReadLine ();
                if (! strResponse.StartsWith ("2"))
                {
                    errorInfo = "UserName error!";
                    return 403;
                }
                sw.WriteLine ("quit");
                errorInfo = String.Empty;
                return 200;

            }
            catch (Exception ee)
            {
                errorInfo = ee.Message.ToString ();
                return 403;
            }
        }
 The calling method of the program:

if (checkEmail ("abc@163.com", out errorInfo) == 200)
{
       return true;
}
This procedure is implemented according to the basic process of SMTP. The basic process of connecting to a mail server to send mail may be like this:
 
  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.
 
 
  The gray part of the code is a conventional email address checking method to check the validity of the address form.
 
  The program uses the System.IO, System.Net.Sockets, and System.Diagnostics namespaces, which are called via checkMail (mailAddress).
 
  Description:
 
  1. This method can further check the validity of the email address, which is a great improvement over only formal verification. For applications that need to verify registration information and send passwords via email address, you can further ensure the effectiveness;
 
  2. Due to the diversity and configurability of the Email server, the sub-program cannot guarantee the universal application of the results;
 
  3. For some large mail servers, it usually has a strong anti-spam function, and may respond to such detection, so it is not suitable for a large number of address detection. For example, during the probing process, I found that the 163.com server stopped responding to the request.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.