---
title: "C# email validation in .NET with a domain check"
url: "https://lookvalid.com/blog/tutorial/csharp-email-validation-dotnet.md"
canonical_url: "https://lookvalid.com/blog/tutorial/csharp-email-validation-dotnet"
last_updated: "2026-11-12"
type: "how-to"
summary: "Validate an email in C# in two layers: MailAddress.TryCreate for syntax, then HttpClient and the email domain check for MX, disposable and role signals."
related: ["https://lookvalid.com/products/email-domain-check.md", "https://lookvalid.com/tools/email-domain-checker.md", "https://lookvalid.com/docs/quickstart.md", "https://lookvalid.com/glossary/disposable-email.md"]
install: "claude mcp add --transport http lookvalid https://lookvalid.com/api/mcp"
---

# C# email validation in .NET with a domain check

> **For AI agents:** the complete index of LookValid pages is [llms.txt](https://lookvalid.com/llms.txt). Every page is also served as markdown at its URL plus .md.

Validate an email in C# in two layers: MailAddress.TryCreate for syntax, then HttpClient and the email domain check for MX, disposable and role signals.

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.

## 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 [6][7]. .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.

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

```csharp
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");
    }
}
```

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

| Input | MailAddress.TryCreate | Email domain check |
| --- | --- | --- |
| ada@example.com | Parses | Checked; one credit when found |
| "Ada" <ada@example.com> | Parses, but Address differs from the input | Never sent: the guard in the code refuses it first |
| user@localhost | Parses | 400 invalid_input: the part after @ needs a top-level domain |
| "a b"@example.com | Parses as a quoted user name | 400 invalid_input: quotes and spaces are not allowed |
| An address on a domain that does not exist | Parses | found false with a reason; nothing charged |
| An address on a disposable provider | Parses | Checked; disposable true, so the program refuses it |

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](https://lookvalid.com/blog/tutorial/nodejs-email-domain-verification.md) and [PHP email validation](https://lookvalid.com/blog/tutorial/php-email-validation-api.md).

## 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](https://lookvalid.com/products/email-domain-check.md) for every response field, try an address in the [email domain checker](https://lookvalid.com/tools/email-domain-checker.md) without a key, or begin with the [quickstart](https://lookvalid.com/docs/quickstart.md).

## Sources

1. [Microsoft Learn: MailAddress class](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress), read 2026-11-05
2. [Microsoft Learn: MailAddress.TryCreate](https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress.trycreate), read 2026-11-05
3. [Microsoft Learn: Guidelines for using HttpClient](https://learn.microsoft.com/en-us/dotnet/fundamentals/networking/http/httpclient-guidelines), read 2026-11-05
4. [Microsoft Learn: HttpClientJsonExtensions.PostAsJsonAsync](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.json.httpclientjsonextensions.postasjsonasync), read 2026-11-05
5. [Microsoft Learn: JsonNamingPolicy.SnakeCaseLower](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonnamingpolicy.snakecaselower), read 2026-11-05
6. [RFC 9110: HTTP Semantics (section 10.2.3, Retry-After)](https://www.rfc-editor.org/rfc/rfc9110.html), read 2026-11-05
7. [RFC 6585: Additional HTTP Status Codes (section 4, 429 Too Many Requests)](https://www.rfc-editor.org/rfc/rfc6585.html), read 2026-11-05
8. [Microsoft Learn: HttpResponseHeaders.RetryAfter](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.headers.httpresponseheaders.retryafter), read 2026-11-05

By LookValid engineering. Published 2026-11-06, updated 2026-11-06.

## Related

- [Email Domain Check API](https://lookvalid.com/products/email-domain-check.md)
- [Free email domain checker (MX, SPF, DMARC)](https://lookvalid.com/tools/email-domain-checker.md)
- [Quickstart](https://lookvalid.com/docs/quickstart.md)
- [What is Disposable email?](https://lookvalid.com/glossary/disposable-email.md)
