Like a good C# user, I use the MailAddress
object to validate email addresses.
A client of mine entered john@gmail.
for his email, which was validated by MailAddress
, and broke my software. I'd expect the code below to throw an exception, but it doesn't.
static void Main(string[] args)
{
string addressmail = string.Empty;
try
{
MailAddress mail = new MailAddress(@"john@gmail.");
addressmail = mail.Address;
}
catch (FormatException)
{
// address is invalid
}
// address is valid
Console.WriteLine(addressmail);
}
Do you know how to catch this kind of bogus mail address?
I think in this case, MS's implementation of a valid email address is incorrect, at least as per RFC822. I haven't actually tried your code, so I'm assuming it does as you say.
There are other ways to validate email addresses, such as actually connecting to the SMTP server and asking it to confirm that the address is valid (as explained here and here). Short of doing that, you will always have a bit of trouble. Personally, I don't think that it's worthwhile to spend too much time validating email address according to some specification (beyond the quick checks we have at our disposal; e.g. your code) - the real test is whether an email is received on that address if you send it. A simple email verification can confirm this, although I know it might not be appropriate in all cases, but in those, you are out of luck.