29

I am trying to send an email using c# using the following code.

MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress, friendlyName);
mail.To.Add(toAddress);
mail.CC.Add(ccAddress);

//set the content
mail.Subject = emailSubject;
mail.Body = emailHeader + "\n" + emailBody;

//send the message
SmtpClient smtp = new SmtpClient(ServerAddress);
smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
mail.IsBodyHtml = true;
smtp.Send(mail);

Now the "toAddress" string that my function recieves might contain a single address, or it might have many, comma delimited addresses.

Now the problem is that, in case of multiple comma delimited addresses, one or two of them might be of the wrong email address format.

So when I try to send an email using this code, I get the exception:

"The specified string is not in the form required for an e-mail address."

Is there any way to validate the comma delimited email addresses? I had read somewhere that the only way to validate an email address is to send an email to it, because the regular expressions to validate an email addreess can be surprisingly huge.

Also, I have no control over the design, or on how that address string comes to my function,I can't add the email validation in the UI, so I am helpless there...

My problem is that the email will not be delivered to ALL the addresses in the comma delimited string, even though only SOME of the addresses are of the wrong format.

Is there any way to properly validate email addresses in .NET? Is there a way to weed out the bad email addresses and send the mail to only the good ones?

1
  • I'm a little confused. Are you trying to validate an email address or just the format of an email address?
    – beyerss
    Jun 16, 2009 at 10:54

13 Answers 13

31

This is code we have on production (even added a comma for you). Normally you shouldn't use try/catch for validation, but it works well here. I believe it's better than trying to recode the validator.

string[] allToAddresses = to.Split(";,".ToCharArray(),
                                 StringSplitOptions.RemoveEmptyEntries)
foreach (string toAddress in allToAddresses)
{
    try
    {
        message.To.Add(toAddress);
    }
    catch (FormatException)
    {
        //do nothing, ill-formed address. 
    }
}
5
  • 4
    Are you sure that every exception thrown by Add implies an illformed address? You should only catch the exceptions that actually do mean a bad address. Your code will prevent you from seeing that one exception that says "something is horribly wrong; I hope someone sees this and does something about it; I'm going to die now; goodbye". Jun 16, 2009 at 11:28
  • 2
    I knew that wouldn't be popular - but yes. Look at msdn.microsoft.com/en-us/library/ms144695.aspx - two exceptions for null and empty, and a FormatException. I guess you can always get an exotic exception (say, out of memory, or something crazy like that), so I'll change it. Thanks.
    – Kobi
    Jun 16, 2009 at 12:51
  • 3
    Also, .NET isn't Java, and Microsoft gets to add exceptions over the course of time. It would be better to fail to catch some exception that actually does imply an invalid email address, than to catch and ignore some exception that implies that something terrible is happening. Jun 16, 2009 at 13:04
  • > illformed address. screw it. screw it indeed good sir. I approve of your "this exception doesn't matter comment"
    – JJS
    Mar 10, 2021 at 23:48
  • 1
    @Quarkly - The opposite is true, this is the only approach that promises the email is valid in .NET, any regex you write will never be the same as this validation (because eventually .NET does it anyway). "RegEx exception" was probably written in the heat of the moment, but specifically for regex, please have a look in my profile - most people think I grew too much on that front. And please treat your QA's better.
    – Kobi
    Mar 11, 2021 at 23:18
24

You could just split the email string on the comma and validate each email address using a simple (or huge) email regex. Or, try creating a MailAddress object; it supports some basic validation of the address too.

8
  • 1
    you got seconds ahead of me with the response so I didn't re-post it... +1
    – AlexDrenea
    Jun 16, 2009 at 10:59
  • 2
    +1. I think the MailAddress constructor is more than sufficient for his current purposes (a quick check before sending for the first time). Jun 16, 2009 at 11:00
  • 1
    You should also note that emails are usually delimited with semicolons, not commas.
    – Kobi
    Jun 16, 2009 at 11:05
  • 1
    Kobi, it used to be... Now only commas are accepted. rstew.blogspot.com/2007/06/specified-string-is-not-in-form.html Jun 16, 2009 at 11:22
  • 2
    FYI, using MailAddress to validate an email address isn't foolproof. It seems to allow some bad addresses that shouldn't get through like "bob.@mysite.com" or "bob..smith@mysite.com". May 4, 2012 at 15:16
24

Currently we are using following function and it is working quite well for us :)

public static bool IsValidEmail(string email)
{
    // source: http://thedailywtf.com/Articles/Validating_Email_Addresses.aspx
    Regex rx = new Regex(
    @"^[-!#$%&'*+/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+/0-9=?A-Z^_a-z{|}~])*@[a-zA-Z](-?[a-zA-Z0-9])*(\.[a-zA-Z](-?[a-zA-Z0-9])*)+$");
    return rx.IsMatch(email);
}

Please use this:

(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
5
  • 4
    That one validates aman@village.i but there are no one letter TLDs. Jun 16, 2009 at 13:16
  • 1
    Points for showing your work, though. All I had to do was to change the regex.
    – Narnian
    Apr 12, 2012 at 14:44
  • The first one in this answer is the best one I've found so far... although will not correctly validate ipv6 or special characters inside quotes. The second one is not good at all sadly. Jan 8, 2013 at 15:16
  • Here this is on Regexr, looks pretty close to bullet proof? regexr.com/48vms Feb 23, 2019 at 19:35
  • Fails on email@123.123.123.123
    – Suraj
    Nov 17, 2020 at 2:43
20

Having 100% RFC-compliant email validation is hard, see this answer for details. In .NET two relatively straightforward ways is to use MailAddress

try {
    new MailAddress("invalid_email");
} catch (FormatException) {
    // invalid
}
// TODO: ask MS to implement MailAddress.TryParse to avoid exception

Or more strict Regex-based approach from MSDN (handles IDN and Regex parsing timeout for .NET 4.5):

// NET 4.0
Boolean mappingInvalid = false;
emailString = Regex.Replace(emailString, @"(@)(.+)$", match => {
    String domainName = match.Groups[2].Value;
    try {
        domainName = new IdnMapping().GetAscii(domainName);
    } catch (ArgumentException) {
        mappingInvalid = true;
    }
    return match.Groups[1].Value + domainName;
});
if (mappingInvalid) {
    return false;
}
return Regex.IsMatch(emailString,
        @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
        RegexOptions.IgnoreCase);
4
  • 2
    The first solution is straightforward, relies on a (probably) very well tested piece of code that all .NET programmers have access to. Good work!
    – Liedman
    Jan 29, 2014 at 9:53
  • @Quarkly, 1/2, sometimes catching a specific exception is the only way to deal with the condition. There are cases where library designers made a mistake and did not allow you to check for the conditions proactively. I.e. there is no MailAddress.TryParse method that would have allowed you to avoid the exceptions. Eric Lippert classifies these as 'vexing' exceptions ericlippert.com/2008/09/10/vexing-exceptions More info here: stackoverflow.com/a/7152374.
    – Dmitry
    Mar 12, 2021 at 19:43
  • As of .NET 5, MailAddress.TryCreate() works nicely for the first solution Oct 21, 2021 at 10:21
  • Note that new MailAddress("test 123@test.com") is valid, but creates the address 123@test,com with „test“ as display name ("test" <123@test.com>). So you might want to check for spaces as well. It's still better than the EmailAddressAttribute though because it catches commas in the domain name, which is a common typo. Feb 6 at 14:48
6
using System.ComponentModel.DataAnnotations;

return new EmailAddressAttribute().IsValid(strIn);
1
  • Unfortunately, unlike new MailAddress("..."), this allows for test@test,com (comma instead of a dot), a very common mistake we get on a weekly basis. Feb 6 at 14:31
5

The following will check that the e-mail address is of the correct form (not it that actually exists):

private bool isEmail(string inputEmail)
{
    Regex re = new Regex(@"^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$",
                  RegexOptions.IgnoreCase);
    return re.IsMatch(inputEmail);
}

I've updated this with a simpler expression (including case insensitivity) in order to hopefully make it a bit clearer.

The following is the basics of the code that will verify that the domain actually exists:

private bool isRealDomain(string inputEmail)
{
    bool isReal = false;
    try
    {
        string[] host = (inputEmail.Split('@'));
        string hostname = host[1];

        IPHostEntry IPhst = Dns.GetHostEntry(hostname);
        IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], 25);
        Socket s = new Socket(endPt.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);
        s.Connect(endPt);
        s.Close();
        isReal = true;
    }
    catch (<specific exceptions here>)
    {
    }

    return isReal;
}

There is a lot more you can do, actually trying to connect for example, to verify that the domain will receive the mail. Plus you'll need to make sure you catch the necessary exceptions and handle them correctly.

9
  • IMHO you have way too many statements inside of the "try" for you to be ignoring all exceptions with a "catch". Any of those could fail for reasons that have nothing to do with the validity of the email address, and you won't know about it. Jun 16, 2009 at 13:02
  • jonelf+stackoverflow@musedoma.museum is a perfectly legal email address but your Regex thinks it's not. Jun 16, 2009 at 13:05
  • @jonelf - I must admit that I "borrowed" the regex and haven't had time to check it out properly. Thanks for the heads up.
    – ChrisF
    Jun 16, 2009 at 14:48
  • @John Saunders - the code is merely there as an example. I'll remove the try...catch if you feel it gets in the way.
    – ChrisF
    Jun 16, 2009 at 14:49
  • @ChrisF: instead, think of setting a good example. You know how many people find these answers and just copy and paste code. You know it's just an example, and I know it's just an example, but many of them don't read before they copy and paste. Jun 16, 2009 at 14:57
3

Microsoft just updated their documentation on validating email and it works great. link: https://learn.microsoft.com/en-us/dotnet/standard/base-types/how-to-verify-that-strings-are-in-valid-email-format

Snippet:

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class RegexUtilities
{
   bool invalid = false;

   public bool IsValidEmail(string strIn)
   {
       invalid = false;
       if (String.IsNullOrEmpty(strIn))
          return false;

       // Use IdnMapping class to convert Unicode domain names.
       try {
          strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper,
                                RegexOptions.None, TimeSpan.FromMilliseconds(200));
       }
       catch (RegexMatchTimeoutException) {
         return false;
       }

        if (invalid)
           return false;

       // Return true if strIn is in valid email format.
       try {
          return Regex.IsMatch(strIn,
                @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
                @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-0-9a-z]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$",
                RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250));
       }
       catch (RegexMatchTimeoutException) {
          return false;
       }
   }

   private string DomainMapper(Match match)
   {
      // IdnMapping class with default property values.
      IdnMapping idn = new IdnMapping();

      string domainName = match.Groups[2].Value;
      try {
         domainName = idn.GetAscii(domainName);
      }
      catch (ArgumentException) {
         invalid = true;
      }
      return match.Groups[1].Value + domainName;
   }
}
2

There does not appear to be a good way to validate email addresses.

I have not found a regex to date which will validate correctly. I have had cases of email addresses being blocked by regex. So our focus is to ensure that the MailMessage does not throw an exception during a send. If it does, we can notify the users. But outside of that, if you give bad email address, you don't get an email.

2

Because none of the other answers appear to show a 100% working regex, I'll have a go. This is taken from production code and does not suffer from the single letter TLD issue (me@mydomain.x).

private bool IsEmailSyntaxValid(string emailToValidate)
{
    return System.Text.RegularExpressions.Regex.IsMatch(emailToValidate,
        @"^([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})(\]?)$");
}

Can't remember where I got this, but as I say, it works for me in production.

2
  • 1
    Downvoting this one, sorry. -- "info@about.museum" does not validate. Jun 5, 2012 at 19:02
  • Ah, no problem. I didn't see that one. Jun 7, 2012 at 16:06
1

You can always use the regex at this site its huge and totally unreadable but it gets most edge cases.

(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:
\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(
?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ 
\t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\0
31]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\
](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+
(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:
(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)
?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\
r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[
 \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)
?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t]
)*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[
 \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*
)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t]
)+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)
*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+
|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r
\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:
\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t
]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031
]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](
?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?
:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?
:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?
:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?
[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] 
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|
\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>
@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"
(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?
:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[
\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-
\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(
?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;
:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([
^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\"
.\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\
]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\
[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\
r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] 
\000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]
|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \0
00-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\
.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,
;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?
:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[
^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]
]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(
?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(
?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[
\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t
])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t
])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?
:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|
\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:
[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\
]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)
?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["
()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)
?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>
@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[
 \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,
;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t]
)*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\
".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?
(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".
\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:
\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\[
"()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])
*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])
+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\
.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z
|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(
?:\r\n)?[ \t])*))*)?;\s*)
1
  • 1
    This is the best - especially I love that it gets it rigth most of the time Mar 3, 2021 at 9:04
0

Yeah, split the emails string on the delimiter and then validate each email address. here's an example, it will fail on the second email address (foo#bar.com). I've used the regular expression from the asp.net regular expression control to validate the addresses.

String email = "bar@foo.com;foo#bar.com";

String expression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

Regex regex = new Regex(expression);

String[] emails = email.Split(new Char[] { ';' });

foreach (String s in emails)
{

    Match m = regex.Match(s);

    if (!m.Success)
     {
        // Validation fails.

     }
}
0
string uname = Convert.ToString(string);
string expression = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";

Regex regex = new Regex(expression);
Match m = regex.Match(uname);

if (m.Success)
{
    emailId = uname; 
}
1
  • just try it for validating any string as email id , it will work. Apr 22, 2014 at 14:04
0

You can use Regex. Just write below code.

public static bool IsValidEmail(this string email)
{
   const string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";    
   var regex = new Regex(pattern, RegexOptions.IgnoreCase);    
   return regex.IsMatch(email);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.