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?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
ashwnacharya
  • 14,601
  • 23
  • 89
  • 112
  • I'm a little confused. Are you trying to validate an email address or just the format of an email address? – beyerss Jun 16 '09 at 10:54

13 Answers13

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. 
    }
}
Kobi
  • 135,331
  • 41
  • 252
  • 292
  • 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". – John Saunders Jun 16 '09 at 11:28
  • 2
    I knew that wouldn't be popular - but yes. Look at http://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 '09 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. – John Saunders Jun 16 '09 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 '21 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 '21 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.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Fredrik Leijon
  • 2,792
  • 18
  • 20
  • 1
    you got seconds ahead of me with the response so I didn't re-post it... +1 – AlexDrenea Jun 16 '09 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). – Matthew Flaschen Jun 16 '09 at 11:00
  • 1
    You should also note that emails are usually delimited with semicolons, not commas. – Kobi Jun 16 '09 at 11:05
  • 1
    Kobi, it used to be... Now only commas are accepted. http://rstew.blogspot.com/2007/06/specified-string-is-not-in-form.html – ashwnacharya Jun 16 '09 at 11:22
  • Oh. I'm outdated. But semicolons are still used commonly, aren't they? Outlook still use them, if that's an indication... Thanks @ashwnacharya. – Kobi Jun 16 '09 at 12:55
  • @Kobi - yeah, Outlook still uses them, as well as OWA (Outlook Web Access). It gets me every time I send an email to 2 people and use a comma, only to get the error "John.Smith,Jane.Doe is not a valid email" – Jared Harley Jun 16 '09 at 22:45
  • 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". – Jacobs Data Solutions May 04 '12 at 15:16
  • Well, the only foolproof way of knowing if the email is correct is to send an email to it with a custom link to click (ie activation links used on most sites these days) – Fredrik Leijon Oct 31 '12 at 14:32
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])+)\])
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
TheVillageIdiot
  • 40,053
  • 20
  • 133
  • 188
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);
Dmitry
  • 17,078
  • 2
  • 44
  • 70
  • 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 '14 at 09: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 https://ericlippert.com/2008/09/10/vexing-exceptions/ More info here: https://stackoverflow.com/a/7152374. – Dmitry Mar 12 '21 at 19:43
  • As of .NET 5, MailAddress.TryCreate() works nicely for the first solution – Mark Willis Oct 21 '21 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. – Oliver Schimmer Feb 06 '23 at 14:48
6
using System.ComponentModel.DataAnnotations;

return new EmailAddressAttribute().IsValid(strIn);
xskxzr
  • 12,442
  • 12
  • 37
  • 77
David Gamache
  • 69
  • 1
  • 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. – Oliver Schimmer Feb 06 '23 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.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • 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. – John Saunders Jun 16 '09 at 13:02
  • jonelf+stackoverflow@musedoma.museum is a perfectly legal email address but your Regex thinks it's not. – Jonas Elfström Jun 16 '09 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 '09 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 '09 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. – John Saunders Jun 16 '09 at 14:57
  • @John - so true. Hopefully with the comments and the it'll be clearer and I'll update the code later. – ChrisF Jun 16 '09 at 15:08
  • @jonelf - I've updated the regex which now copes with "+" in e-mails. Testing it again also showed up an error in some subsequent code so thanks again for pointing it out. – ChrisF Jun 16 '09 at 17:34
  • What about non ASCII domains? What about TLDs with more that 4 chars? And the culture looks wrong too. – CodesInChaos Sep 18 '11 at 14:15
  • @CodeInChaos - I never said it was perfect ;) Though why not edit it? – ChrisF Sep 18 '11 at 20:10
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;
   }
}
aslam
  • 31
  • 1
  • 5
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.

Ricardo Altamirano
  • 14,650
  • 21
  • 72
  • 105
Valamas
  • 24,169
  • 25
  • 107
  • 177
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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ryan O'Neill
  • 5,410
  • 4
  • 46
  • 69
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])*))*|(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 \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])*))*|(?:[^()<>@,;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[^()<>@,;:\\".\[\] \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*)
Peter
  • 37,042
  • 39
  • 142
  • 198
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.

     }
}
cjk
  • 45,739
  • 9
  • 81
  • 112
Phil
  • 3,568
  • 3
  • 34
  • 40
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; 
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
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);
}
Naveen
  • 1,441
  • 2
  • 16
  • 41