Validating email addresses in .NET - Handy Tip

If you've ever written any code that sends emails before, I'm pretty sure that you've had to validate the email addresses that are entered by users. Email address validation can be tricky at the best of times and with international domain names in email addresses, almost anything is possible. In my opinion, there is no 100% reliable way of validating email addresses, you just have to make sure that it conforms to as reasonable a standard as possible.

Validating email addresses in .NET

Using client side validation, such as the HTML5 email input type is a great way of detecting invalid email addresses. However, there may be times when you need to validate on the server. When validating email addresses in .NET, I have always previously used some pretty gnarly Regex expressions. Some of them worked, some of them didn't work that well. I recently discovered a little trick that you can use to validate email addresses, and best of all - it uses a built-in .NET class.

The System.Net.Mail namespace has a built-in class called MailAddress. If this method is passed an invalid email address, it will simply throw an error which you can use to your advantage.

In the code above, I have created a simple method that passes an email address to the MailAddress class. If the email address is invalid, the MailAddress class will throw an error which we can catch and return as a false.

The best thing about this class is that it conforms to the RFC5322 specification for email addresses, so you are able to take advantage of this without writing loads of code. While this validation isn't perfect and some dodgy emails will still slip through, it's a pretty good start.