title: How can I validate an email address in Active Directory and retrieve the username associated with that email address?
body: <p>I am busy with a little project where users can query their domain username's by providing their email address.  So what needs to happen is that the user would fill in a <code>TextBox</code> with their email address, then it needs to check that email address in Active Directory and if found send the username to that email address.</p>
  <p>This is the code I have done but it seems to not check and keeps saying the email address is valid, although I know that email does not exist in my domain.</p>
  <pre><code>protected void btnForgotEmail_Click(object sender, EventArgs e)
      {
          string strADPath = &quot;Server Address&quot;;
          string strUsername = &quot;admin Username&quot;;
          string strPassword = &quot;Admin Password&quot;;
          string emailAddress = txtForgotUsername.Text.ToString();
          try
          {
              PrincipalContext context = new PrincipalContext(ContextType.Domain, strADPath, strUsername, strPassword);
              UserPrincipal user = new UserPrincipal(context);
              user.EmailAddress = emailAddress;
              PrincipalSearcher ps = new PrincipalSearcher();
              ps.QueryFilter = user;
              var results = ps.FindAll().ToList();
              if(results == null)
              {
                  error.Text = &quot;The Email Address  &quot; + &quot;'&quot; + emailAddress + &quot;'&quot; + &quot;  Does Not Exist In This Domain.  Please Contact The Administrator For Assistance&quot;;
              }
              else
              {
                  messageAD.Text = &quot;The Email Address  &quot; + &quot;'&quot; + emailAddress + &quot;'&quot; + &quot;  Has Been Validated&quot; + &quot;&lt;br&gt;&quot; + &quot;Your Username has been sent Via Email&quot;;
       
              ==&gt; Code to send email with username &lt;==
              }
          }
          catch (Exception ex)
          {
              error.Text = ex.Message;
          }
      }
  </code></pre>
  <p>Thanks</p>