Tutorials

C# email validation in .NET with a domain check

Email validation in C# usually stops at a parser, which tells you the text is shaped like an address and nothing about whether mail to it can arrive. This tutorial uses MailAddress.TryCreate for the shape and HttpClient with the LookValid email domain check for the rest, and ends with a signup decision you can call from an ASP.NET Core handler or a console job.

By LookValid engineering. Published 2026-11-06.

Layer one: parse the address with MailAddress

MailAddress.TryCreate builds a MailAddress from a string and returns false instead of throwing when it cannot 2. The class is made for composing mail, so it accepts more than a bare address: it also reads the display-name form "Ada" <ada@example.com>, quoted user names and bracketed domain literals 1. A validation step that only checks the return value would let "Ada" <ada@example.com> through, so the code below also requires Address to equal the trimmed input, which keeps only a bare user@host.

Microsoft is explicit about the limit of this layer: the class may accept an address that other mail servers do not 1. Treat a pass as "it parses", and let the second layer decide whether the domain can receive mail.

Layer two: ask whether the domain can receive mail

The LookValid email domain check reads the domain's public DNS and returns whether it publishes MX records, whether it is a known disposable provider, whether the local part is a role mailbox such as info@, and a deliverability_signal of good, risky or undeliverable. It never contacts the mailbox. A found result costs 1 credit, and found: false costs nothing.

Create one HttpClient and reuse it. Microsoft recommends a static or singleton instance (or short-lived clients from IHttpClientFactory), because each instance owns a connection pool and creating one per request wastes sockets 3. PostAsJsonAsync serializes the value you pass as JSON in the request body 4, and System.Text.Json has a SnakeCaseLower naming policy 5, which maps the C# property DeliverabilitySignal to the API field deliverability_signal. The code targets .NET 8 or later.

The full program

A 429 status means the client sent too many requests, and the server says how long to wait in the Retry-After header, which holds either an HTTP-date or a number of seconds 67. .NET parses it for you into response.Headers.RetryAfter, whose Delta is the seconds form 8. Our API sends seconds. Transport failures surface as HttpRequestException, and a request that outlives HttpClient.Timeout surfaces as TaskCanceledException, so the loop retries both with a growing delay.

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Net.Mail;
using System.Text.Json;
​
Console.WriteLine(await EmailChecker.CheckSignupAsync("new.user@example.org"));
​
public sealed record DomainData(bool Disposable, bool RoleAccount, string DeliverabilitySignal);
public sealed record DomainCheck(bool Found, string? Reason, DomainData? Data);
public sealed record ApiError(string Code, string Message, bool Retryable);
public sealed record ApiErrorBody(ApiError Error);
public sealed record Decision(bool Allow, string? Why = null, bool Review = false);
​
public static class EmailChecker
{
    private static readonly JsonSerializerOptions Json = new() { PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower };
​
    // One client for the life of the process: each instance owns a connection pool.
    private static readonly HttpClient Http = new()
    {
        BaseAddress = new Uri("https://YOUR_API_HOST"),
        Timeout = TimeSpan.FromSeconds(10),
        DefaultRequestHeaders =
        {
            Authorization = new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("LOOKVALID_API_KEY")),
        },
    };
​
    public static async Task<DomainCheck> LookupAsync(string email, int maxAttempts = 4)
    {
        for (var attempt = 1; ; attempt++)
        {
            HttpResponseMessage response;
            try
            {
                response = await Http.PostAsJsonAsync("/v1/email-domain-check", new { email }, Json);
            }
            catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException)
            {
                if (attempt >= maxAttempts) throw;
                await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
                continue;
            }
​
            using (response)
            {
                if (response.StatusCode == HttpStatusCode.TooManyRequests && attempt < maxAttempts)
                {
                    await Task.Delay(response.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(1));
                    continue;
                }
                if (response.IsSuccessStatusCode)
                {
                    return (await response.Content.ReadFromJsonAsync<DomainCheck>(Json))!;
                }
​
                var error = (await response.Content.ReadFromJsonAsync<ApiErrorBody>(Json))?.Error;
                if (error is { Retryable: true } && attempt < maxAttempts)
                {
                    await Task.Delay(TimeSpan.FromSeconds(Math.Pow(2, attempt)));
                    continue;
                }
                throw new InvalidOperationException($"{error?.Code}: {error?.Message}");
            }
        }
    }
​
    public static async Task<Decision> CheckSignupAsync(string input)
    {
        var text = input.Trim();
        // MailAddress also accepts "Name" <user@host>; requiring Address to equal the input keeps bare addresses only.
        if (!MailAddress.TryCreate(text, out var parsed) || !string.Equals(parsed.Address, text, StringComparison.OrdinalIgnoreCase))
        {
            return new Decision(false, "not shaped like an email address");
        }
​
        var result = await LookupAsync(parsed.Address);
        if (!result.Found) return new Decision(false, result.Reason);
​
        var data = result.Data!;
        if (data.Disposable) return new Decision(false, "disposable domain");
        if (data.DeliverabilitySignal == "undeliverable") return new Decision(false, "domain accepts no mail");
        return new Decision(true, Review: data.DeliverabilitySignal == "risky");
    }
}

A top-level program: parse, check the domain, retry on 429

Save it as Program.cs in a console project (dotnet new console), export LOOKVALID_API_KEY, and run dotnet run. The sample address uses example.org, which publishes a null MX record to say it takes no mail, so the check returns undeliverable and the program prints Decision { Allow = False, Why = domain accepts no mail, Review = False }.

Where the two layers disagree

MailAddress is more permissive than the API in a few places. The API trims the input, lowercases it, converts an internationalized domain to Punycode, and refuses forms that mail systems rarely use, answering 400 with the invalid_input code and charging nothing. The loop above does not retry a 400, because its retryable flag is false, so the call throws and your handler can show the message.

How each layer treats common inputs
InputMailAddress.TryCreateEmail domain check
ada@example.comParsesChecked; one credit when found
"Ada" <ada@example.com>Parses, but Address differs from the inputNever sent: the guard in the code refuses it first
user@localhostParses400 invalid_input: the part after @ needs a top-level domain
"a b"@example.comParses as a quoted user name400 invalid_input: quotes and spaces are not allowed
An address on a domain that does not existParsesfound false with a reason; nothing charged
An address on a disposable providerParsesChecked; disposable true, so the program refuses it

How each layer treats common inputs

So the two layers do different jobs: the parser keeps obvious junk out of the request, and the API answers the question the parser cannot. Wrap CheckSignupAsync in a try and treat an InvalidOperationException carrying invalid_input as "ask for another address". For the same flow in other languages see verify email domains in Node.js and PHP email validation.

Run it

  1. Create a console project with the .NET 8 SDK or later: dotnet new console.
  2. Replace Program.cs with the code above and export LOOKVALID_API_KEY.
  3. Run dotnet run and read the Allow, Why and Review values.

Read the email domain check product page for every response field, try an address in the email domain checker without a key, or begin with the quickstart.

Sources

  1. Microsoft Learn: MailAddress class, read 2026-11-05
  2. Microsoft Learn: MailAddress.TryCreate, read 2026-11-05
  3. Microsoft Learn: Guidelines for using HttpClient, read 2026-11-05
  4. Microsoft Learn: HttpClientJsonExtensions.PostAsJsonAsync, read 2026-11-05
  5. Microsoft Learn: JsonNamingPolicy.SnakeCaseLower, read 2026-11-05
  6. RFC 9110: HTTP Semantics (section 10.2.3, Retry-After), read 2026-11-05
  7. RFC 6585: Additional HTTP Status Codes (section 4, 429 Too Many Requests), read 2026-11-05
  8. Microsoft Learn: HttpResponseHeaders.RetryAfter, read 2026-11-05