How to validate email addresses in C#

Build an email validator in C# step by step: syntax checks, MX lookups, disposable-domain detection, typo suggestions, an ASP.NET Core minimal API endpoint and a validation attribute.

What we'll build

A regular expression, MailAddress or [EmailAddress] can tell you an address looks right. None of them can tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build an EmailValidator.ValidateAsync() method in C# that checks all of those and returns one of four statuses:

StatusMeaningTypical action
validWell formed, and the domain accepts mailAccept
invalidBad syntax, no such domain, or no mail serverReject and ask the user to fix it
riskyDisposable, a likely typo, a role account, or no MX recordsYour call: block, warn, or flag
unknownDNS failed temporarilyAccept and check again later

You'll need .NET 10, the current long-term support release. .NET has no built-in way to look up MX records, so add DnsClient.NET:

dotnet add package DnsClient

Every snippet was tested with .NET 10, ASP.NET Core 10 and DnsClient 1.8. Want to see the end result first? The free email checker runs the same checks.

1. Check the syntax

Start with the check that needs no network. Instead of one huge regular expression, split the address at the last @ and check each part separately. The rules stay readable, and you can say exactly what's wrong:

EmailSyntax.cs
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;

namespace EmailCheck;

public sealed record SyntaxResult(bool Ok, string? Reason = null, string Local = "", string Domain = "", string Normalized = "");

public static partial class EmailSyntax
{
    // RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
    [GeneratedRegex(@"^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+$")]
    private static partial Regex Atom();

    // A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
    [GeneratedRegex(@"^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$")]
    private static partial Regex Label();

    private static readonly IdnMapping Idn = new() { UseStd3AsciiRules = true };

    /// <summary>Lower-cases a domain and converts international names to punycode, or returns null.</summary>
    private static string? ToAsciiDomain(string domain)
    {
        try { return Idn.GetAscii(domain.Trim().TrimEnd('.')).ToLowerInvariant(); }
        catch (ArgumentException) { return null; }
    }

    public static SyntaxResult Check(string? input)
    {
        var email = (input ?? "").Trim();
        if (email.Length > 254) return new(false, "too_long");

        var at = email.LastIndexOf('@');
        if (at <= 0 || at == email.Length - 1) return new(false, "missing_at_or_part");

        var local = email[..at];
        if (Encoding.UTF8.GetByteCount(local) > 64) return new(false, "local_part_too_long");
        // Split keeps empty parts, so leading, trailing and doubled dots fail.
        if (!local.Split('.').All(atom => Atom().IsMatch(atom))) return new(false, "invalid_local_part");

        var domain = ToAsciiDomain(email[(at + 1)..]);
        var labels = domain?.Split('.') ?? [];
        if (labels.Length < 2 || labels[^1].All(char.IsAsciiDigit) || !labels.All(l => Label().IsMatch(l)))
            return new(false, "invalid_domain");

        return new(true, null, local, domain!, $"{local.ToLowerInvariant()}@{domain}");
    }
}

Notes on the code:

  • IdnMapping.GetAscii() converts international domains to punycode (münchen.de becomes xn--mnchen-3ya.de), which is the form DNS needs. With UseStd3AsciiRules it also rejects characters that can't appear in a host name.
  • [GeneratedRegex] compiles the patterns at build time, so there's no start-up cost.
  • Split('.') keeps empty parts, so .jane, jane. and ja..ne all fail with no extra rules.
  • The local part limit is 64 bytes (RFC 5321), so the length is measured in UTF-8 bytes, not Length.
Using MailAddress? new MailAddress(email) accepts display names and quoted local parts, such as "Jane" <jane@example.com>, which don't belong in a sign-up form. A dedicated check like this one is stricter and gives you a reason.

Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.

2. Check the domain's MX records

A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail. With ThrowDnsErrors off, DnsClient returns the DNS response code instead of throwing, so a missing domain, a domain without MX records and DNS trouble each get the right status:

DnsCheck.cs
using DnsClient;
using DnsClient.Protocol;

namespace EmailCheck;

public sealed record DomainCheck(string Status, string? Reason = null, IReadOnlyList<string>? Mx = null);

public static class DnsCheck
{
    // Uses the system's DNS servers, with a short timeout so a slow DNS server can't stall a sign-up.
    public static ILookupClient Client { get; set; } = new LookupClient(new LookupClientOptions
    {
        Timeout = TimeSpan.FromSeconds(3),
        Retries = 1,
        ThrowDnsErrors = false, // report NXDOMAIN and SERVFAIL as response codes, not exceptions
        UseCache = false,       // step 3 adds our own cache
    });

    public static async Task<DomainCheck> CheckAsync(string domain)
    {
        IDnsQueryResponse response;
        try
        {
            response = await Client.QueryAsync(domain, QueryType.MX);
        }
        catch (DnsResponseException)
        {
            // Timeouts and network errors are temporary. Don't blame the user.
            return new("unknown", "dns_error");
        }

        if (response.Header.ResponseCode == DnsHeaderResponseCode.NotExistentDomain)
            return new("invalid", "domain_not_found");
        if (response.HasError)
            return new("unknown", "dns_error"); // SERVFAIL, REFUSED…

        var mx = response.Answers.MxRecords().OrderBy(r => r.Preference).ToList();
        // RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
        if (mx.Count == 1 && mx[0].Exchange.Value == ".")
            return new("invalid", "domain_rejects_mail");
        if (mx.Count > 0)
            return new("ok", Mx: mx.Select(r => r.Exchange.Value.TrimEnd('.')).ToList());

        // No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
        foreach (var type in new[] { QueryType.A, QueryType.AAAA })
        {
            try
            {
                if ((await Client.QueryAsync(domain, type)).Answers.Count > 0) return new("risky", "no_mx_records");
            }
            catch (DnsResponseException) { }
        }
        return new("invalid", "no_mail_server");
    }
}
ResultMeaningStatus
MX records returnedThe domain accepts mailok
One MX record with an empty name"Null MX" (RFC 7505): the domain accepts no mailinvalid
ResponseCode is NotExistentDomainThe domain doesn't existinvalid
No error, but no MX in the answersThe domain exists but has no MX records, so check A/AAAArisky or invalid
Another response code, or a DnsResponseExceptionSERVFAIL or a timeout: DNS trouble, not the user's faultunknown

Keep the timeout short, so a slow DNS server can't hold up a sign-up, and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment.

3. Cache DNS lookups

Most of your users share a handful of domains like gmail.com and outlook.com. An ASP.NET Core app is one long-running process, so a shared dictionary saves most lookups:

DnsCache.cs
using System.Collections.Concurrent;

namespace EmailCheck;

public static class DnsCache
{
    private static readonly ConcurrentDictionary<string, (DomainCheck Result, DateTimeOffset Expires)> Cache = new();

    public static async Task<DomainCheck> CheckAsync(string domain)
    {
        if (Cache.TryGetValue(domain, out var hit) && hit.Expires > DateTimeOffset.UtcNow) return hit.Result;

        var result = await DnsCheck.CheckAsync(domain);
        // Don't remember temporary failures.
        if (result.Status != "unknown") Cache[domain] = (result, DateTimeOffset.UtcNow.AddHours(1));
        return result;
    }
}

ConcurrentDictionary is safe to use from every request at once. If you already use IMemoryCache or HybridCache, use that with the same one-hour expiry instead. Either way, don't cache failed lookups.

4. Detect disposable domains

Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list into your project:

curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf

Then copy it to the build output by adding <None Include="disposable_email_blocklist.conf" CopyToOutputDirectory="PreserveNewest" /> to an ItemGroup in your .csproj:

Disposable.cs
namespace EmailCheck;

public static class Disposable
{
    // One domain per line, loaded once. A HashSet makes each lookup instant.
    private static readonly HashSet<string> Blocklist = File
        .ReadLines(Path.Combine(AppContext.BaseDirectory, "disposable_email_blocklist.conf"))
        .Select(line => line.Trim())
        .Where(line => line.Length > 0)
        .ToHashSet();

    /// <summary>Checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com".</summary>
    public static bool IsDisposable(string domain)
    {
        var labels = domain.Split('.');
        return Enumerable.Range(0, labels.Length - 1).Any(i => Blocklist.Contains(string.Join('.', labels[i..])));
    }
}

Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job and redeploy, or load it from a file you refresh.

The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a DidYouMean suggestion for a disposable address. Read more about how disposable email detection works.

5. Flag role accounts and suggest typo fixes

Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:

Extras.cs
namespace EmailCheck;

public static class Extras
{
    private static readonly HashSet<string> RoleAccounts =
    [
        "admin", "billing", "contact", "help", "hello", "info", "marketing", "no-reply",
        "noreply", "office", "postmaster", "sales", "support", "team", "webmaster",
    ];

    // Ignore "+tag" sub-addressing: "support+billing" is still "support".
    public static bool IsRoleAccount(string local) => RoleAccounts.Contains(local.ToLowerInvariant().Split('+')[0]);

    // Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
    // too, or they'd be "corrected" to the provider one letter away.
    private static readonly string[] PopularDomains =
    [
        "gmail.com", "googlemail.com", "yahoo.com", "ymail.com", "yahoo.co.uk", "hotmail.com",
        "hotmail.co.uk", "outlook.com", "live.com", "msn.com", "icloud.com", "me.com", "mac.com",
        "aol.com", "mail.com", "gmx.com", "gmx.de", "proton.me", "protonmail.com",
    ];

    /// <summary>Levenshtein distance: the number of single-character edits between two strings.</summary>
    public static int EditDistance(string a, string b)
    {
        var prev = Enumerable.Range(0, b.Length + 1).ToArray();
        for (var i = 1; i <= a.Length; i++)
        {
            var row = new int[b.Length + 1];
            row[0] = i;
            for (var j = 1; j <= b.Length; j++)
                row[j] = Math.Min(Math.Min(prev[j] + 1, row[j - 1] + 1), prev[j - 1] + (a[i - 1] == b[j - 1] ? 0 : 1));
            prev = row;
        }
        return prev[b.Length];
    }

    /// <summary>"gmial.com" → "gmail.com"; null when the domain is fine or nothing is close.</summary>
    public static string? SuggestDomain(string domain)
    {
        if (PopularDomains.Contains(domain)) return null;
        var best = PopularDomains.MinBy(candidate => EditDistance(domain, candidate))!;
        // Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
        return EditDistance(domain, best) <= (domain.Length <= 6 ? 1 : 2) ? best : null;
    }
}

The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain.

Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.

6. Put it together

Now run the checks from cheapest to most expensive and return a single verdict:

EmailValidator.cs
namespace EmailCheck;

/// <summary>Status is "valid", "invalid", "risky" or "unknown".</summary>
public sealed record Verdict(string Status, string Reason, string? Email = null, string? DidYouMean = null);

public static class EmailValidator
{
    public static async Task<Verdict> ValidateAsync(string? input)
    {
        var syntax = EmailSyntax.Check(input);
        if (!syntax.Ok) return new("invalid", syntax.Reason!);

        var suggestion = Extras.SuggestDomain(syntax.Domain);
        var didYouMean = suggestion is null ? null : $"{syntax.Local}@{suggestion}";

        var dns = await DnsCache.CheckAsync(syntax.Domain);
        if (dns.Status is "invalid" or "unknown") return new(dns.Status, dns.Reason!, syntax.Normalized, didYouMean);

        // The domain can receive mail. Now look for risk signals, most serious first.
        string? reason =
            Disposable.IsDisposable(syntax.Domain) ? "disposable"
            : suggestion is not null ? "possible_typo"
            : dns.Status == "risky" ? dns.Reason
            : Extras.IsRoleAccount(syntax.Local) ? "role_based"
            : null;
        return reason is null
            ? new("valid", "mail_server_found", syntax.Normalized, didYouMean)
            : new("risky", reason, syntax.Normalized, didYouMean);
    }
}

It returns these results for a range of inputs:

InputstatusreasonDidYouMean
jane@gmail.comvalidmail_server_foundnull
joe@gamil.comriskypossible_typojoe@gmail.com
test@mailinator.comriskydisposablenull
support@acme.ioriskyrole_basednull
x@no-such-domain.exampleinvaliddomain_not_foundnull
not-an-emailinvalidmissing_at_or_partnull

7. Use it in ASP.NET Core

A typical sign-up policy is to reject invalid and disposable addresses, accept everything else, and pass the typo suggestion back so the front end can ask "Did you mean …?". As a minimal API endpoint:

Program.cs
using EmailCheck;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapPost("/signup", async (SignupRequest request) =>
{
    var result = await EmailValidator.ValidateAsync(request.Email);

    if (result.Status == "invalid" || result.Reason == "disposable")
    {
        return Results.UnprocessableEntity(new
        {
            error = result.Reason == "disposable"
                ? "Please use a permanent email address."
                : "That email address can't receive mail.",
            didYouMean = result.DidYouMean,
        });
    }

    // "unknown" means DNS had a hiccup. Accept the address and check it again later.
    // await users.CreateAsync(result.Email);
    return Results.Created((string?)null, new { ok = true, email = result.Email, didYouMean = result.DidYouMean });
});

app.Run();

public record SignupRequest(string? Email);

public partial class Program; // lets the test project start the app

For MVC models, Razor Pages or Blazor forms, wrap the same check in a validation attribute and use it next to [EmailAddress]:

DeliverableAttribute.cs
using System.ComponentModel.DataAnnotations;

namespace EmailCheck;

/// <summary>Rejects addresses that can't receive mail and disposable inboxes. Use next to [EmailAddress].</summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter)]
public sealed class DeliverableAttribute : ValidationAttribute
{
    protected override ValidationResult? IsValid(object? value, ValidationContext context)
    {
        if (value is not string email) return ValidationResult.Success; // leave missing values to [Required]

        // ValidationAttribute is synchronous; the DNS lookup is cached, so later calls are fast.
        var result = EmailValidator.ValidateAsync(email).GetAwaiter().GetResult();
        if (result.Status == "invalid") return new ValidationResult("That email address can't receive mail.");
        if (result.Reason == "disposable") return new ValidationResult("Please use a permanent email address.");
        return ValidationResult.Success;
    }
}

[Required, EmailAddress, Deliverable] public string Email { get; set; } then runs all three. Validation attributes are synchronous, which is why it waits on the async check. The minimal API endpoint above stays fully async. Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.

8. Test it

The syntax check has no side effects, so an xUnit theory covers it:

SyntaxTests.cs
using EmailCheck;

public class SyntaxTests
{
    [Theory]
    [InlineData("jane@example.com")]
    [InlineData("jane.doe+news@example.co.uk")]
    [InlineData("user@münchen.de")]
    public void AcceptsNormalAddresses(string email) => Assert.True(EmailSyntax.Check(email).Ok);

    [Theory]
    [InlineData("")]
    [InlineData("jane")]
    [InlineData("@example.com")]
    [InlineData("jane@")]
    [InlineData("a..b@example.com")]
    [InlineData("jane@example")]
    [InlineData("jane@-example.com")]
    public void RejectsMalformedAddresses(string email) => Assert.False(EmailSyntax.Check(email).Ok);
}

For the DNS checks, point DnsClient at a local test DNS server with new LookupClient(new LookupClientOptions(new NameServer(IPAddress.Loopback, 5353))). Then your test suite doesn't depend on the internet. That's how we tested every result on this page, including the endpoint with WebApplicationFactory.

What about checking that the mailbox exists?

You could go further with TcpClient: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.

For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.

Or use an email validation API

Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request. As a typed HttpClient:

ApiClient.cs
using System.Net.Http.Json;

namespace EmailCheck;

public sealed record ApiResult(string? Email, string Status, string Reason, string? Did_You_Mean = null);

public sealed class ValidateEmailApi(HttpClient http)
{
    // Register with: builder.Services.AddHttpClient<ValidateEmailApi>(c => {
    //     c.BaseAddress = new Uri("https://validateemail.io/v1/");
    //     c.DefaultRequestHeaders.Authorization = new("Bearer", builder.Configuration["ValidateEmail:Key"]);
    // });

    public async Task<ApiResult> ValidateAsync(string email)
    {
        try
        {
            using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
            var response = await http.PostAsJsonAsync("validate", new { email }, cts.Token);
            response.EnsureSuccessStatusCode();
            return (await response.Content.ReadFromJsonAsync<ApiResult>(cts.Token))!;
        }
        catch (Exception e) when (e is HttpRequestException or TaskCanceledException)
        {
            // Never block a sign-up because the validator is slow or unreachable.
            Console.Error.WriteLine($"Email validation unavailable: {e.Message}");
            return new ApiResult(email, "unknown", "validator_unavailable");
        }
    }

    /// <summary>Validates any number of addresses, 100 per request.</summary>
    public async Task<List<ApiResult>> ValidateListAsync(IEnumerable<string> emails)
    {
        var results = new List<ApiResult>();
        foreach (var chunk in emails.Chunk(100))
        {
            var response = await http.PostAsJsonAsync("validate/batch", new { emails = chunk });
            response.EnsureSuccessStatusCode();
            results.AddRange((await response.Content.ReadFromJsonAsync<BatchResponse>())!.Results);
        }
        return results;
    }

    private sealed record BatchResponse(List<ApiResult> Results);
}

If the API is slow or unreachable, ValidateAsync() returns unknown instead of throwing, so a network problem never blocks a sign-up. The response has the same status, reason and did_you_mean fields used in this guide, plus a score and the result of every individual check.

Using an AI coding assistant? Paste this prompt and it will wire up the API for you:

Prompt for Cursor, Claude Code, Lovable or Copilot
Add email validation to the sign-up endpoint of this ASP.NET Core app using the validateemail.io API (reference: https://validateemail.io/llms.txt).

- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.

Frequently asked questions

Is [EmailAddress] enough to validate an email in ASP.NET Core?

[EmailAddress] only checks that the value contains an @ with something on both sides. It can't tell you whether the domain exists or accepts mail, or whether the address is disposable or mistyped, so pair it with an MX lookup and the other checks in this guide, as the [Deliverable] attribute in step 7 does.

How do I look up MX records in C#?

.NET has no built-in MX lookup; Dns.GetHostAddressesAsync() only returns IP addresses. Use DnsClient.NET: new LookupClient().QueryAsync(domain, QueryType.MX). With ThrowDnsErrors = false, a response code of NotExistentDomain means the domain doesn't exist.

Should I use MailAddress to validate emails in C#?

MailAddress is a parser for addresses in email headers, so it accepts display names and quoted local parts that a sign-up form shouldn't. It's fine as a rough format check, but it doesn't look up the domain.

Can C# check that a mailbox exists without sending an email?

You can try by opening a TcpClient to the domain's mail server on port 25 and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.