Verifying email addresses in C# is a common task for ensuring data quality. You have several options, and we'll explore five distinct methods with working code snippets. We will also examine the pitfalls of these traditional approaches and see how Abstract API provides a more reliable solution.
How to Implement Email Validation in C#
Here are three common methods to validate email addresses in C#. Each approach uses different built-in .NET features to check if an email format is correct before you accept it.
Use of System.Net.Mail.MailAddress
The MailAddress class constructor attempts to parse the provided email string. It follows the same grammar rules as the older SmtpClient. This method is fast and has no external dependencies.
If the constructor cannot build a valid internal representation of the address, it throws a FormatException. You can catch this exception to determine if the validation fails.
The class also canonicalizes the address, which means it converts it to a standard format. This allows you to compare the output with the original string for an exact match.
bool IsValidMailAddress(string email)
{
try
{
var addr = new MailAddress(email);
return addr.Address.Equals(email, StringComparison.OrdinalIgnoreCase);
}
catch (FormatException)
{
return false;
}
}
Application of DataAnnotations EmailAddressAttribute
The EmailAddressAttribute provides a declarative way to validate emails, similar to ASP.NET Core model validation. Internally, it applies a compact regular expression to check the email format.
This approach is convenient if you already use DataAnnotations or FluentValidation, as they call the same IsValid method. It can also be injected into pipeline components and supports error message localization.
static readonly EmailAddressAttribute _attr = new();
bool IsValidWithAttribute(string email) => _attr.IsValid(email);
Regex with IdnMapping Normalization
This method combines regular expressions with Internationalized Domain Name (IDN) support. It first converts the domain part of the email to ASCII characters using the IdnMapping class.
After normalization, it applies a regex pattern to validate the structure. The code also specifies timeouts for the regex operations to protect against potential ReDoS attacks.
bool IsValidRegex(string email)
{
if (string.IsNullOrWhiteSpace(email)) return false;
try
{
email = Regex.Replace(email, @"(@)(.+)$", m =>
{
var idn = new IdnMapping();
return m.Groups[1].Value + idn.GetAscii(m.Groups[2].Value);
}, RegexOptions.None, TimeSpan.FromMilliseconds(200));
return Regex.IsMatch(
email,
@"^[^@\s]+@[^@\s]+\.[^@\s]+$",
RegexOptions.IgnoreCase,
TimeSpan.FromMilliseconds(250));
}
catch
{
return false;
}
}
Challenges of Email Validation in C#
The previous methods seem straightforward but have significant drawbacks. They often struggle with complex email standards, international characters, and the actual deliverability of an address, which leads to unreliable results.
- Regular expressions, used by `EmailAddressAttribute` and `Regex` methods, cannot fully parse RFC 5322 grammar. This limitation forces a difficult trade-off between the rejection of valid emails and the acceptance of invalid ones, as complex structures are not supported.
- Framework helpers like `MailAddress` and `EmailAddressAttribute` accept technically invalid formats, such as addresses that end with a period. This makes it risky to trust the platform's built-in validation and difficult to debug or extend when business rules change.
- Modern emails use international characters (UTF-8/IDN), but .NET support is inconsistent. Methods like `Regex with IdnMapping` attempt normalization but can still reject valid users or fail to detect spoofed addresses due to framework implementation gaps.
- Syntax validation alone does not confirm deliverability. An address can pass checks from `MailAddress` or a regex pattern yet be undeliverable due to a missing MX record or a server that blocks the connection. These issues are undetectable with code-side validation.
Validate Emails with Abstract API
Ensure your C# application collects valid user emails to improve data quality and deliverability.
Get started for free
How Abstract API Handles Email Validation in C#
Abstract API addresses the core weaknesses of traditional validation methods. It combines multiple checks into a single, comprehensive API call.
- It moves beyond simple regex syntax checks to confirm if a domain accepts mail, if a mailbox exists, and if an address is from a disposable service.
- The API eliminates the need to build and maintain custom MX or SMTP probes. It performs these checks on its servers and returns a simple boolean result.
- It provides up-to-date checks for disposable and free email providers. The API uses machine-learned lists, so your application stays current without manual data updates.
- It offers a granular quality score instead of a simple pass or fail result. This score allows you to define custom risk thresholds for your application's logic.
How to Add Abstract API to Your Dev Environment
Once you understand Abstract's capabilities, you can add its email validation API to your project with ease.
- First, sign up at Abstract API and get your Email Validation API key from the dashboard.
- Add the System.Net.Http.Json package to your solution. This package comes with .NET 6 and later versions.
- You should store the API key in environment variables or appsettings.json. Do not hard-code it.
- Then, add an HttpClient singleton through IHttpClientFactory or a new instance.
- Create a Plain Old CLR Object (POCO) that matches the API response structure.
- Finally, call the API endpoint, deserialize the JSON response, and use the Deliverability and QualityScore fields.
dotnet add package System.Net.Http.Json
Sample Email Validation Implementation with Abstract API
The C# code below shows a practical implementation. It defines data records to match the API's JSON response. It also creates an asynchronous function to call the API and demonstrates how to use that function with a sample email address.
public record EmailValidationResponse(
string Email,
string Autocorrect,
string Deliverability,
float Quality_Score,
BoolField Is_Valid_Format,
BoolField Is_Free_Email,
BoolField Is_Disposable_Email,
BoolField Is_Mx_Found,
BoolField Is_Smtp_Valid);
public record BoolField(bool Value, string Text);
static async Task<EmailValidationResponse> ValidateAsync(string email, string apiKey, HttpClient http)
{
var uri = $"https://emailvalidation.abstractapi.com/v1/?api_key={apiKey}&email={Uri.EscapeDataString(email)}";
return await http.GetFromJsonAsync<EmailValidationResponse>(uri);
}
// usage
var http = new HttpClient();
var result = await ValidateAsync("johnsmith@gmail.com", Environment.GetEnvironmentVariable("ABSTRACT_KEY"), http);
if (result.Deliverability != "DELIVERABLE" || result.Quality_Score < 0.8f) { /* flag or reject */ }
The API returns a detailed JSON object like the one below. This response provides a clear deliverability status and a quality score. It also includes boolean flags for format validity, free or disposable providers, MX record presence, and SMTP connection success. This data gives you a full picture of the email's quality.
{
"email":"johnsmith@gmail.com", "autocorrect":"",
"deliverability":"DELIVERABLE", "quality_score":0.9,
"is_valid_format":{"value":true,"text":"TRUE"},
"is_free_email":{"value":true,"text":"TRUE"},
"is_disposable_email":{"value":false,"text":"FALSE"},
"is_mx_found":{"value":true,"text":"TRUE"},
"is_smtp_valid":{"value":true,"text":"TRUE"}
}
Final Thoughts
Traditional validation methods often stop at syntax and require complex, self-maintained probes. These checks fail to confirm real deliverability. Abstract API provides a complete solution. It bundles multiple checks into one simple call for a clear verdict on email quality. To reliably validate user emails, consider an account on Abstract API to get your free API key.
Validate Emails with Abstract API
Ensure data quality and improve deliverability by implementing proper email validation in your C# project.
Get started for free