DEV Community

Sofia Tarhonska
Sofia Tarhonska

Posted on • Originally published at mailtrap.io

How to Validate an Email Address in C#

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.

using System;
using System.Collections.Generic;
using System.Net.Mail;

namespace EmailAddressValidationConsoleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var emailAddresses = new List<string>
            {
                // Valid email addresses
                "tony@example.com",
                "tony.stark@example.net",
                "tony@example.co.uk",
                "tony@example",

                // Invalid email addresses
                "tony.example.com",
                "tony@stark@example.net",
                "tony@.example.co.uk"
            };

            Console.Title = "Email address validation";

            foreach (var emailAddress in emailAddresses)
                Console.WriteLine($"{emailAddress,-37} --> {(IsValid(emailAddress) ? "Valid" : "Invalid")}");

            Console.ReadLine();
        }

        private static bool IsValid(string email)
        { 
            var valid = true;

            try
            { 
                var emailAddress = new MailAddress(email);
            }
            catch
            {
                valid = false;
            }

            return valid;
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

Image description

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)$
Enter fullscreen mode Exit fullscreen mode

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:

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace EmailAddressValidationConsoleApp
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var emailAddresses = new List<string>
            {
                // Valid email addresses based on regex defined
                "tony@example.com",
                "tony.stark@example.net",
                "tony.stark@example.gov",
                "TONY@EXAMPLE.GOV",

                // Invalid email addresses based on regex defined
                "tony@example",
                "tony@example.co.uk",
                "tony@example.me"
            };

            foreach (var emailAddress in emailAddresses)
            {
                Console.WriteLine($"{emailAddress} is" + (IsValid(emailAddress) ? " a valid" : " an invalid") + " email address.");
            }

            Console.ReadLine();
        }

        private static bool IsValid(string email)
        { 
            string regex = @"^[^@\s]+@[^@\s]+\.(com|net|org|gov)$";

            return Regex.IsMatch(email, regex, RegexOptions.IgnoreCase);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

Image description

Result of email validation using regex

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:

^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$
Enter fullscreen mode Exit fullscreen mode

Quite long, right?

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

\.?$
Enter fullscreen mode Exit fullscreen mode

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.

tony@example.com.
Enter fullscreen mode Exit fullscreen mode

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:

Image description

The structure of an ASP.NET Core MVC project

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

using System.ComponentModel.DataAnnotations;

namespace MyContacts.Models
{
    public class ContactViewModel
    {
        public string Name { get; set; }

        [Required]
        // Attribute to validate the email address
        [EmailAddress(ErrorMessage = "Invalid email address.")] 
        public string Email { get; set; }
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

@model ContactViewModel;

@{
    ViewData["Title"] = "Contact Page";
}

<div class="row">
    <div class="col-md-8 offset-md-2">
        <form>
            <div class="form-group">
                <label asp-for="Name"></label>
                <input asp-for="Name" type="text" class="form-control">
            </div>
            <div class="form-group">
                <label asp-for="Email"></label>
                <input asp-for="Email" type="email" class="form-control">
                <span asp-validation-for="Email" class="text-danger"></span>
            </div>
            <div class="form-group">
                <button type="submit" class="btn btn-outline-success">Save</button>
            </div>
        </form>
    </div>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Enter fullscreen mode Exit fullscreen mode

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

<span asp-validation-for="Email" class="text-danger"></span>
Enter fullscreen mode Exit fullscreen mode

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:

jquery.validate.min.js
jquery.validate.unobtrusive.min.js
Enter fullscreen mode Exit fullscreen mode

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:

Image description
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:

[Required]
[EmailAddress(ErrorMessage = "Invalid email address.")] 
[RegularExpression(@"^[^@\s]+@[^@\s]+\.(com|net|org|gov)$", ErrorMessage = "Invalid pattern.")]
public string Email { get; set; }
Enter fullscreen mode Exit fullscreen mode

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.

Image description
Form validation using RegularExpression attribute

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:

Install-Package GemBox.Email
Enter fullscreen mode Exit fullscreen mode

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

using System;
using System.Collections.Generic;
using GemBox.Email;

namespace GemboxEmail
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // If you have a Professional version, put your license key below.
            ComponentInfo.SetLicense("FREE-LIMITED-KEY");

            // --- 1. Validate a single email address.

            // The email address has an invalid format.
            string email = " <invalid.address@gmail.com";
            MailAddressValidationResult result = MailAddressValidator.Validate(email);
            Console.WriteLine($"{email,-37} --> {result.Status}");

            // --- 2. Validate multiple email addresses.

            var emails = new List<MailAddress>()
            {
                // The email address does not exist.
                new MailAddress("no-address@gmail.com"),

                // The domain does not exist.
                new MailAddress("no-domain@gmail123123123.com"),

                // The email address is valid.
                new MailAddress("support@mailtrap.io")
            };

            var validationResults = MailAddressValidator.Validate(emails);

            for (var i = 0; i < validationResults.Count; i++)
                Console.WriteLine($"{emails[i],-37} --> {validationResults[i].Status}");

            Console.ReadLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Here’s the output of the above code.

Image description
GemBox email validation

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:

Install-Package EASendMail
Enter fullscreen mode Exit fullscreen mode

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

using System;

namespace EASendMail
{
    public class Program
    {
        public static void Main(string[] args)
        {
            try
            {
                // Use "TryIt" as a license code for evaluation use
                var oMail = new SmtpMail("TryIt");

                // Change it to yours
                oMail.From = "youremail@domain.com";

                // The email address does not exist
                oMail.To = "no-address@gmail.com";

                // Do not set the SMTP server address
                SmtpServer oServer = new SmtpServer("");

                SmtpClient oSmtp = new SmtpClient();
                oSmtp.TestRecipients(oServer, oMail);

                Console.WriteLine("Email address was verified!");
            }
            catch (Exception ep)
            {
                Console.WriteLine("Failed to test email with the following error:");
                Console.WriteLine(ep.Message);
            }

            Console.ReadLine();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

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:

Image description
EASendMail email validation

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?!


Here we are! Thanks for reading our guide on regular expression for email in C# that was originally published on Mailtrap Blog.

Top comments (0)