C# email validation: MailAddress, EmailAddressAttribute and a real mailbox check
· Updated · 7 min read · Tutorials
C# email validation usually starts with System.Net.Mail.MailAddress or [EmailAddress] from System.ComponentModel.DataAnnotations. Both only check that the string looks roughly like an address. Neither tells you whether the domain exists or the mailbox accepts mail. For that you need a DNS and SMTP check, which in practice means an HTTP call to a verification API from your backend. This post shows what the built-in options accept, a stricter syntax check, and a typed HttpClient that calls pingutil's /v1/verify with sane timeouts.
The examples target .NET 8 and ASP.NET Core minimal APIs. Nothing needs a NuGet package beyond what ships with the SDK. A shorter setup summary is on the ASP.NET Core integration page.
What the built-in validators actually check
| Approach | What it checks | Accepts | Misses |
|---|---|---|---|
[EmailAddress] (DataAnnotations) |
Exactly one @, not first or last |
a@b, a b@c, x@y..z |
Everything about the domain and mailbox |
new MailAddress(s) / MailAddress.TryCreate |
RFC 5322 style parsing | Jane <jane@acme.com>, user@localhost, quoted local parts |
Whether the domain exists or takes mail |
| Your own regex | Whatever you wrote | Depends | Domain, MX, mailbox, typos |
| Verification API | Syntax, disposable list, DNS/MX, SMTP mailbox, catch-all | n/a | Ownership (only a confirmation email proves that) |
EmailAddressAttribute is deliberately loose
The attribute's implementation in .NET (Core and later) is short. You can read it in the dotnet/runtime source: it returns true when the value is null, false when it isn't a string, and otherwise true only if there is exactly one @ that is neither the first nor the last character. The old .NET Framework version used a long regex; the newer one dropped it on purpose to avoid rejecting valid international addresses.
That means [EmailAddress] passes hello@world, my name@company and x@y..z: anything with one @ somewhere in the middle. It rejects x@@y and @acme.com, and that's about it. Treat it as "the user typed something address-shaped", nothing more. And because null passes, add [Required] when the field is mandatory.
MailAddress is a parser, not a validator
MailAddress exists to build message headers, so it accepts everything a header might contain. new MailAddress("Jane Doe <jane@acme.com>") succeeds and sets Address to jane@acme.com and DisplayName to Jane Doe. It also accepts a host without a dot, like user@localhost, which is legal in SMTP but never what a signup form wants.
Since .NET 5 there's MailAddress.TryCreate, which avoids using exceptions for control flow. The API docs list the overloads. If you use it, compare the parsed address with the input so display-name forms are rejected:
using System.Net.Mail;
static bool LooksLikeEmail(string? input)
{
if (string.IsNullOrWhiteSpace(input) || input.Length > 320) return false;
var trimmed = input.Trim();
if (!MailAddress.TryCreate(trimmed, out var parsed)) return false;
// Reject "Jane <jane@acme.com>" and similar header forms.
if (!string.Equals(parsed.Address, trimmed, StringComparison.OrdinalIgnoreCase)) return false;
// Require a dot in the host and no leading/trailing dot.
var host = parsed.Host;
return host.Contains('.') && !host.StartsWith('.') && !host.EndsWith('.');
}
This is a reasonable syntax gate. It still says yes to jane@acme-typo-domain.com, jane@gmial.com and zz9xq3@mailinator.com. Our post on why an email regex is never enough covers the full list of what syntax checks miss.
Why you can't finish the job inside .NET
The next checks are a DNS lookup for MX records and an SMTP conversation (RCPT TO) with the recipient's mail server. .NET has no built-in MX lookup in System.Net.Dns (it resolves A/AAAA only), so you'd need a third-party DNS library. The SMTP part needs outbound port 25, which most cloud hosts block by default, and it needs handling for greylisting, catch-all domains and servers that rate-limit unknown senders.
That's the part an API does for you. pingutil's /v1/verify runs syntax, the disposable-domain list, DNS/MX, an SMTP RCPT TO (no message is sent) and a catch-all probe, then returns one of four statuses:
status |
Meaning | Typical action at signup |
|---|---|---|
valid |
The server confirmed the mailbox | Accept |
invalid |
Bad syntax, disposable domain, no mail server, or mailbox rejected | Block with a clear message |
risky |
Catch-all domain, role address, full mailbox, randomized local part | Accept, maybe flag |
unknown |
The server wouldn't give a definite answer (greylisting, timeout, block) | Accept, re-check later |
Catch-all domains come back risky with reason: "accept_all", never valid, because a server that accepts every address can't confirm any of them. The full reason list is in email verification statuses explained.
A typed HttpClient for /v1/verify
The response fields are snake_case (did_you_mean, mx_host), so use JsonNamingPolicy.SnakeCaseLower, added in .NET 8.
// PingutilClient.cs
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
public sealed record VerifyChecks(
bool Syntax,
bool Disposable,
bool FreeProvider,
bool RoleBased,
bool Randomized,
bool? DomainExists,
bool? HasMx,
string Mailbox,
bool? CatchAll);
public sealed record EmailVerification(
string? Email,
string Input,
string Status, // valid | invalid | risky | unknown
string Reason, // mailbox_exists, accept_all, greylisted, ...
int Score, // 0-100
string? DidYouMean,
VerifyChecks Checks,
string? MxHost,
bool Cached,
string CheckedAt);
public sealed class PingutilClient(HttpClient http)
{
private static readonly JsonSerializerOptions Json = new()
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
PropertyNameCaseInsensitive = true,
};
public async Task<EmailVerification?> VerifyAsync(string email, CancellationToken ct = default)
{
using var resp = await http.PostAsJsonAsync("v1/verify", new { email }, Json, ct);
if (resp.StatusCode == HttpStatusCode.TooManyRequests) return null; // rate_limited or quota_exceeded
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadFromJsonAsync<EmailVerification>(Json, ct);
}
}
Register it with IHttpClientFactory so connections are pooled and the key lives in configuration, not code:
// Program.cs
using System.Net.Http.Headers;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<PingutilClient>(client =>
{
client.BaseAddress = new Uri("https://pingutil.com/");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", builder.Configuration["Pingutil:ApiKey"]);
// Ceiling for background jobs. Interactive paths pass a shorter token (below).
client.Timeout = TimeSpan.FromSeconds(30);
});
var app = builder.Build();
Set the key with dotnet user-secrets set "Pingutil:ApiKey" "pk_live_..." in development and an environment variable (Pingutil__ApiKey) in production.
Using it in a signup endpoint
Most checks take one to five seconds, and a slow mail server can take up to about 25. A person on a signup form shouldn't wait that long, so give the call its own short deadline and treat a timeout as "unknown, let them in":
app.MapPost("/signup", async (SignupRequest req, PingutilClient pingutil, ILogger<Program> log) =>
{
if (!LooksLikeEmail(req.Email))
return Results.BadRequest(new { error = "Enter a valid email address." });
EmailVerification? v = null;
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
try
{
v = await pingutil.VerifyAsync(req.Email.Trim(), cts.Token);
}
catch (Exception ex) when (ex is OperationCanceledException or HttpRequestException)
{
log.LogWarning(ex, "verification skipped for signup");
}
if (v is { Status: "invalid" })
{
var message = v.DidYouMean is not null
? $"That address doesn't look deliverable. Did you mean {v.DidYouMean}?"
: "That address can't receive email. Please use another one.";
return Results.BadRequest(new { error = message, did_you_mean = v.DidYouMean });
}
// valid, risky, unknown, or no answer: create the account and send a confirmation email.
var user = await CreateUserAsync(req.Email.Trim(), flagged: v?.Status is "risky" or "unknown" or null);
return Results.Ok(new { id = user.Id });
});
app.Run();
public sealed record SignupRequest(string Email, string Password);
CreateUserAsync is your own code. A few things in this handler are deliberate:
- Only
invalidblocks. Catch-all domains are common at real companies, andunknownis usually the remote server's mood, not the user's fault. did_you_meangoes back to the client. Typos likegmial.comare the most fixable error, and the user is still on the page. See catching email typos at signup for UI patterns.- Failures fail open. A timeout, a 5xx or a 429 never stops a signup. Queue a background re-check for flagged accounts instead.
- Confirmation email still happens. Verification says a mailbox exists; only a link or code proves the person owns it.
Handling 429 properly
The API returns HTTP 429 with an error field in the JSON body. Two values matter: rate_limited (more than 60 requests a minute for your account; the body includes retry_after_seconds and the response has a Retry-After header) and quota_exceeded (the daily verification budget is used up, so retrying today won't help). In a background job, read the body and branch:
if (resp.StatusCode == HttpStatusCode.TooManyRequests)
{
using var doc = await JsonDocument.ParseAsync(await resp.Content.ReadAsStreamAsync(ct), cancellationToken: ct);
var error = doc.RootElement.TryGetProperty("error", out var e) ? e.GetString() : null;
var wait = doc.RootElement.TryGetProperty("retry_after_seconds", out var r) ? r.GetInt32() : 30;
if (error == "quota_exceeded") throw new InvalidOperationException("daily verification quota reached");
await Task.Delay(TimeSpan.FromSeconds(wait), ct);
// then retry
}
For lists, POST /v1/verify/batch takes { "emails": [...] } with up to 50 addresses and returns { "results": [...] } in the same order. Results are cached on our side for 30 days, but cached answers still count toward the daily budget, so deduplicate before you send.
What to keep from this
Use MailAddress.TryCreate plus an exact-match check as your syntax gate, keep [EmailAddress] for model binding if you like it, and do the real check with one HTTP call from the server. The API reference has every field, the verification demo lets you try addresses before writing code, and the email verification API integration guide covers retries, caching and status policy for any language.
Questions people ask
- What is the best way to validate an email address in C#?
- Use MailAddress.TryCreate or a short regex to reject input that is obviously malformed, then check the domain and mailbox with a verification API from your backend. Syntax checks alone accept addresses on domains that don't exist and mailboxes nobody owns.
- Does EmailAddressAttribute check that the email exists?
- No. In current .NET it only checks that the string contains exactly one @ character that is neither the first nor the last character. It does not look at the domain, DNS or the mailbox, and it returns true for null, so pair it with Required.
- Is new MailAddress() a good email validator?
- It is a parser, not a validator. It accepts display-name forms (a name followed by the address in angle brackets), domains without a dot and other inputs you probably don't want in a signup form. Compare the parsed Address with the original input if you use it.