Join us

How to Validate an Email Address in C#

Sending_-Emails_Codeignite_C_Featured1-1920x997.png

Email validation is crucial to help you maintain a list of valid and real email addresses. Keeping mistyped and non-existent emails will result in high bounces, low opens, and few conversions. Worse, it can also damage your sending reputation, which can be difficult to repair. 

Hence, adding email validation in your C# code is essential. And fortunately, relatively painless! In this post, you’ll learn several options on how to validate email in C#. 

Let’s start!

Validate email addresses using the MailAddress class

Microsoft provides built-in support for sending emails to an SMTP server through the System.Net.Mail namespace. It contains the MailAddress class, which is used to store the sender and recipient email addresses. You can utilize this class to validate emails.

Note: This article focuses on email validation. If you’re looking for how to send and receive an email in C# using the classic SMTP protocol, see Send and Receive Emails in ASP.NET C#.

To see how we can use the MailAddress class to check whether an email is valid, let’s create a new C# Console App using Visual Studio. Either the .NET Framework or Core will work. Then, copy-paste the following code into the Program.cs file.

Let’s look at the IsValid method in the above code. It validates a single email by initializing a new instance of the MailAddress class using the string passed in the parameter. If succeeded, the email is considered valid, and the method returns true.

Run the project, and you’ll see an output as follows:

Result of email validation using the MailAddress class

Based on the above screenshot, you can see the results for the email addresses provided. One interesting thing here is, it validates the email tony@example (without .com or .net or .co.uk) as valid. 

You may want to have more control over the format you consider valid. In case you want to prevent emails without a top-level domain, you can try using regex. 

Validate email addresses with regex

A regular expression often called regex for short. It’s a set of symbols that define a text pattern.  

Email addresses, newsletters, text messages—all these are text. Using a regex, you can define what pattern an email must have so that it’s considered a valid address, based on your needs. 

Suppose you want to define only email addresses with .com, .net, .org, and .gov top-level domains are valid. You can use the following regex:

^[^@\s]+@[^@\s]+\.(com|net|org|gov)$

Copy

See the following interpretation for the regex above:

  • ^ — Begin the match at the start of the string.
  • [^@\s]+ — Match one or more occurrences of any character other than the @ character or whitespace
  • @ — Match the @ character
  • [^@\s]+ — Match one or more occurrences of any character other than the @ character or whitespace.
  • \. — Match a single period character.
  • (com|net|org|gov) — Match com or net or org or gov.
  • $ — Stop matching at the end of the string.

Regex is very flexible and powerful to check the email format. However, you can’t use it to verify whether an email address actually exists. 

Regular expression for email in C#

To use a regex in your C# code, you need to include the System.Text.RegularExpressions namespace. See an example code below:

The IsValid method in the above code returns true if the email string matches the regex and false if it doesn’t. Notice that the regex is using the RegexOptions.IgnoreCase flag. This option ignores case-sensitive matching.

If you run the code, you’ll get the result as follows:

Based on the result above, the regex has validated emails with .com, .net, and .gov as valid addresses. Also, see that TONY@EXAMPLE.GOV validates to true. It’s because we set the regex to ignore case-sensitive matching. 

There is no single regex that fits all cases

Let’s look at another example. The following is a regex used by Microsoft in their EmailAddressAttribute class:

Quite long, right?

Yet, there is this interesting part at the very end of the regex. 

The above symbols will allow a dot (“.”) at the end of an email address. Test the following email using the above regex. Expectedly, the result will show that it’s a valid email.

So, the “perfect” regex defined by someone else does not necessarily mean that it will be the same for you. Additionally, the more reliable the regex you try to write, the pattern can become complex and difficult to debug or improve. 

Validate Email Addresses using Data Annotations

By validating user input, you can ensure that valid data is entered into your database. Moreover, it helps users enter accurate information as smoothly as possible while making as few mistakes as possible. 

You can take advantage of the System.ComponentModel.DataAnnotations namespace to create client-side validations without too many lines of code. It contains attribute classes for validating user inputs, including email addresses.

Let’s start with the EmailAddress attribute.

Using EmailAddress attribute

We will start by creating a new .NET Core Web Application project. Then, we will add a simple form that allows a user to enter their name and email. We will also validate their email address.

Follow the simple steps below to create the new project:

  • Open Visual Studio, then click File > New > Project. 
  • Select ASP.NET Core Web Application from the project type list. 
  • Give your project a name, for example, MyContacts. After that, click the Create button.
  • Select ASP.NET Core Web App (Model-View-Controller) from templates.
  • Click the Create button again to finish the wizard, and you’re ready to go!

Once you’ve created the project, open Solution Explorer. You will see the structure of your project, as the following screenshot shows:

Let’s add a new class under the Models folder and name it ContactViewModel. Copy-paste the following code into the new class:

Notice that the above code requires the System.ComponentModel.DataAnnotations namespace. Also, see that the Email property has two validation attributes applied to it. Those are EmailAddress and Required attributes.

Under the Views/Home folder, look for the Index.cshtml file. Then, copy-paste the following code into the file: 

Notice that below the Email textbox, we have a span element:

The element will display the error message “Invalid email address.” whenever an invalid email is entered.

At the bottom of the code, the script renders the _ValidationScriptsPartial file. If you expand the Shared folder, you will find a file named _ValidationScriptsPartial.cshtml there. Open it, and you will see that the validations specifically need these jQuery scripts:

Now, let’s run the project by clicking the “Run” button in the toolbar. Try inputting several email addresses. When the code detects an email as invalid, it will display an error message under the Email text box, as the following image shows:

Form validation using EmailAddress attribute

The EmailAddressAttribute is quite useful for validating an email address. However, its purpose is just to prevent small typing mistakes. To make the result more reliable, you can add a RegularExpression attribute.

Combination with RegularExpression attribute

You can apply more than one validation attribute to a property in your model class. See the following code snippet as an example: 

Modify your ContactViewModel class to use the above code for the Email property. 

Now, rerun the code and see that the regex validation is also applied.

Form validation using RegularExpression attribute

From the above image, we can see that tony@example.com.au is considered invalid. This is because the regex attribute defines only email addresses with .com, .net, .org, and .gov. as valid. 

If you’re using external libraries

Many external email solutions support integration with .NET code. To name just a few : SendGrid, GemBox.Email, Aspose.Email for .NET, EASendEmail, and many more. 

Usually, they have their own methods to validate email addresses. Some of them even provide detailed results on the domain validation, mail server validation, and the existence of the email address itself. So, if you’re using an external library to send emails, you might want to utilize their validation methods.

Let’s now discuss these two libraries: Gembox.Email and EASendMail

GemBox.Email

GemBox.Email is a .NET component that allows you to read, write, receive, and send emails efficiently from your code using the POP, IMAP, SMTP, and EWS protocols.

GemBox.Email’s features for email validations:

  • Email syntax verification — to check if the email address conforms to IETF/RFC standards.
  • Domain name validation — to check if the domain name exists.
  • Email server validation — to check if the mail server is available. 
  • Mailbox verification — to check the existence of the specified email address.

They provide methods that enable you to validate a single or a list of email addresses from your C# or VB.NET code.

You can  install it by running the following command in the Package Manager Console:

See an example C# Console App code below that uses GemBox.Email to validate email addresses. 

Here’s the output of the above code. 

You can see the different values returned by the method represent the results of the validation. 

Note: The validation process can be affected by multiple factors, like DNS settings, firewalls, and ISP settings. After you run the code, you might see the validation result for the first email only. The rest might take longer, and some of them might return ServerConnectionError because it failed to connect to the GemBox server. In case your code doesn’t work, and you’re unsure about what causes it, try to contact your IT Support (or maybe even the GemBox Support Team). 

EASendMail

EASendMail offers support to work with email for various environments, including C#, VB.NET, Delphi, C++/CLI, and many others. They also support several protocols, such as SMTP, SSL, EWS, TLS, Live OAUTH, S/MIME, HTML, Gmail OAUTH, and many more.

You can install EASendMail in your .NET Framework project by entering the following command in the Package Manager Console:

To test if an email exists in the real world, they provide the TestRecipients method. See an example code below:

The above code shows how to use EASendMail’s TestRecipients method to validate an email address. 

Use “TryIt” as the license code for evaluation use (it usually works for 1-2 months). If the license code is incorrect, you’ll get an “Invalid License Code” exception. Also, note that you need to pass an empty string to the SmtpServer. Otherwise, you will be testing whether the specified SMTP server will accept the email address.

Here’s the output of the above code:

The above result shows that the recipient’s email address does not exist. It suggests you double-check for typos and unnecessary spaces.

Note: Again, the validation process can be affected by multiple factors, like firewalls, DNS settings, and ISP settings. You will get a “connection attempt failed” error if it can’t connect to the EASendMail server. In case your code doesn’t work, and you’re unsure about what causes it, try to contact your IT Support (or maybe even GemBox Support Team). 

What’s next?

We’ve explored several options to validate email addresses using C#. By doing email validation, you are one step further to reaching out to real customers. 

The next thing to do is testing whether the emails are sent out as expected. However, when doing this kind of testing in Development and Staging environments, you might spam your real customers.

A solution you may want to try is using Mailtrap! It’s a safe testing environment for emails sent from pre-production environments. By using Mailtrap, you don’t need to worry that your testing emails will spam real users or flood your own inbox. How cool is that?!

That's it! Thank you for reading our guide on regular expression for email validation in C# that was originally published on Mailtrap Blog by Piotr Malek.


Pawfives by

Only registered users can post comments. Please, login or signup.

Start blogging about your favorite technologies, reach more readers and earn rewards!

Join other developers and claim your FAUN account now!

User Popularity
807

Influence

81k

Total Hits

49

Posts