views:

769

answers:

8

Hi how can i validate email in c# winforms ?

+2  A: 

This page has a good regular expression matching email addresses.

Remember this is only a formal check. To check whether an email address really exists, you have to send an actual email to the address and check the mail server's response.

And even if this succeeds, the SMTP server might be configured to ignore invalid recipient addresses.

devio
A: 

You can use a regular expression to validate it. There are various different ones floating about, but the more comprehensive ones I've used are quite long, as shown here

AdaTheDev
+1  A: 

You can use Regular Expressions to validate Email addresses:

RegEx reg=new RegEx(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}$")
if(rx.IsMatch("email string"))
    //valid email
TheVillageIdiot
This will only work if it is case-insensitive. Include `RegexOptions.IgnoreCase`
Dinah
+1  A: 

If you want to validate the address format, you should probably use a regular expression. There are thousands of examples out there, so I'll let you find and pick the best one.

If you want to validate that an address exists, this article gives some pointers about how to do so, without giving any specific code examples.

Chris
indeed a good link explaining in PHP how to establish connection in order to very the remote server, although it has nothing to do with C#
Junior Mayhé
A: 

The best way is to split it into two at the '@' and validate mailbox-portion and domain-portion separately. I know there are reg-ex's floating about but these can get complicated fairly quickly.

Section 3.4 of RFC2822 fully defines a valid email address: look for the specification for addr-spec and dot-atom.

In essence the mailbox portion is a string of one or more characters that are either alphanumeric or one of !, #, $, %, &, ', *, +, -, /, = ?, ^, _, `, {, |, }, ~ and a fullstop '.'. The domain portion follows similar rules.

Given the flexibility, the easiest way may simply be a string check to say does it have a single '@', then check the mailbox and domain parts seperately to see if they contain characters not in the set above. Whether this is performed with a regexp or some other way is your own choice.

Chris J
+2  A: 

The best way would be to forward this validation task to .NET itself:

public bool IsValidEmailAddress (string email)
{
    try
    {
        MailAddress ma = new MailAddress (email);

        return true;
    }
   catch
   {
        return false;
   }
}

Granted, it will fire false positives on some technically valid email addresses (with non-latin characters, for example), but since it won't be able to send to those addresses anyway, you can as well filter them out from the start.

User
IsValidEmailAddress returns true even if the TLD is missing. e.g. myname@mycompany succeeds.
Mark Maslar
@Mark Maslar: Yes, I know. These are valid email addresses, though you don't usually get one of those.
User
I am admin@localhost!
Axarydax
A: 

I've used the Regex from a JQuery plugin that validates on the client side:

    public static bool ValidEmail(string email)
{
  var regex = new Regex(

@"^((([a-z]|\d|[!#\$%&'*+-\/=\?\^{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+))|((\x22)((((\x20|\x09)(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))(((\x20|\x09)(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))).)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|.||~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))).?$", RegexOptions.Compiled);

  return regex.IsMatch(email);
}
TWith2Sugars
A: 

Using Chris' article, I made an extension method for strings which ties together a DNSLookup library (credit is given to Bill Andreozzi, [email protected] in the source), the Minimal Telnet implementation by Tom Janssens (http://www.corebvba.be) and my own RegEx to to validate email addresses:

/// <summary>
/// The regular expression to test the string against.
/// </summary>
private static readonly Regex validEmailRegex = new Regex(
    @"^(([^<>()[\]\\.,;:\s@\""]+"
    + @"(\.[^<>()[\]\\.,;:\s@\""]+)*)|(\"".+\""))@"
    + @"((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}"
    + @"\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+"
    + @"[a-zA-Z]{2,}))$",
    RegexOptions.Compiled);

/// <summary>
/// Determines whether the specified string is a valid email address.
/// </summary>
/// <param name="value">
/// The string to validate.
/// </param>
/// <returns>
/// <c>true</c> if the specified string is a valid email address;
/// otherwise, <c>false</c>.
/// </returns>
public static bool IsValidEmailAddress(this string value)
{
    if (!validEmailRegex.IsMatch(value))
    {
        return false;
    }

    var mailServer = new DNS().LookupMX(value.Split('@')[1]);

    if (!mailServer.MoveNext())
    {
        return false;
    }

    var telnet = new TelnetConnection(((DNS_MX_DATA)((DNS_WRAPPER)mailServer.Current).dnsData).pNameExchange, 25);

    try
    {
        if (!TelnetCompare(telnet.Read(), "220"))
        {
            return false;
        }

        telnet.WriteLine("helo hi");
        if (!TelnetCompare(telnet.Read(), "250"))
        {
            return false;
        }

        telnet.WriteLine("mail from: " + value);
        if (!TelnetCompare(telnet.Read(), "250"))
        {
            return false;
        }

        telnet.WriteLine("rcpt to: " + value);
        if (!TelnetCompare(telnet.Read(), "250"))
        {
            return false;
        }
    }
    finally
    {
        telnet.WriteLine("quit");
    }

    return true;
}

/// <summary>
/// Compares two strings for length and content from the Telnet stream.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="response">The desired response.</param>
/// <returns>true if the response is the first characters if the input,
/// false otherwise</returns>
private static bool TelnetCompare(string input, string response)
{
    if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(response))
    {
        return false;
    }

    if (input.Length < response.Length)
    {
        return false;
    }

    return string.CompareOrdinal(input.Substring(0, response.Length), response) == 0;
}
Jesse C. Slicer