If you try and create a MailAddress object in .NET with an IDN domain, it will fail with a FormatException.
To fix this, I have created two small helper functions.
One that gets a MailAddress object that works both with non-IDN and IDN domain names.
The other uses that one to validate if an email address is valid.
This is pretty smart, since people have a tendency to validate email addresses using different regular expressions, and none of them really works in all cases.
So first - here is how to get an email address for both types of domains:
public static MailAddress GetMailAddress(string email, string name) { if (string.IsNullOrEmpty(email) || email.Contains(' ') || email.Count(c => c == '@') > 1) { return null; } try { return string.IsNullOrEmpty(name) ? new MailAddress(email) : new MailAddress(email, name); } catch (FormatException) { if (!email.Contains("@") || email.Count(c => c == '@') != 1) { return null; } string[] parts = email.Split('@'); try { IdnMapping mapping = new IdnMapping(); return string.IsNullOrEmpty(name) ? new MailAddress(string.Concat(mapping.GetAscii(parts[0]), "@", mapping.GetAscii(parts[1]))) : new MailAddress(string.Concat(mapping.GetAscii(parts[0]), "@", mapping.GetAscii(parts[1])), name); } catch (ArgumentException) { return null; } catch (FormatException) { return null; } } }
And here is how to use it to validate email addresses:
public static bool ValidateEmailAddress(string email) { return GetMailAddress(email, string.Empty) != null; }
This is smart, since we don't use any regular expressions for it, but just uses .NET's own implementation to validate addresses.
That is really it - and it works everywhere, not just in Sitecore :-)