Protect new mailboxesFresh mailboxes burn fast on a dirty list

Verify every lead before the first send and keep bounces low from day one.

Verify 25 emails free →
Product Bulk verificationReal-time APISignup form widget Catch-all detectionRole and disposable flagsFree email checker
Solutions Cold email agenciesSales teams and SDRsDevelopers and SaaS InstantlySmartleadApollolemlistClayHubSpotMailchimpWoodpeckerReply.ioSaleshandyZapierGoogle SheetsMaken8n All integrations
Mailboxes Google Workspace mailboxesOutlook mailboxesNew cold domain checklist
Compare vs ZeroBouncevs NeverBouncevs Emailable Pricing comparedCredit expiry comparedAll comparisons
Resources GuidesBounce rate benchmarksHow many bounces burn a domain?MX records MX lookupDomain health reportEmail list cleanerAll MX Tools
Pricing

Email verification API for C#

Verify one address or a whole list from C# in a few lines. The API is plain HTTPS and JSON: no SDK needed, one bearer key, and the examples below are complete and runnable.

Updated 2026-11-24

Illustration for "Email verification API for C#"

Validating an email address in C# usually starts with MailAddress.TryCreate or [EmailAddress]. Both check the format only. Neither can tell you whether the mailbox exists, and in real lists that is where nearly all the bad addresses are. This page shows the format check first, then how to verify the mailbox itself with HttpClient: one address or a whole list, with no NuGet packages.

TL;DR

  • EmailAddressAttribute only checks for a single @ that is neither first nor last. In our data, just 100 of 779,784 addresses failed syntax, while 7.6% were undeliverable.
  • The Mail Exchange API is plain HTTPS and JSON at https://mailexchange.com/api/v1. No SDK needed.
  • POST /verify checks one address and usually answers in a few seconds. POST /lists checks up to 100,000 addresses and you poll for the result.
  • Each result has a state: deliverable, risky, undeliverable or unknown. The decision function below turns that into send, separate, skip, remove or retry.
  • Handle three statuses and you are done: 202 (still checking), 402 (out of credits) and 429 (slow down).

Get an API key and set up the project

Create an API key in your account (sign up, then open API keys). Every request sends the key as Authorization: Bearer your_key. Keep it in an environment variable, as the examples do, and out of source control. Checks are paid from your plan's monthly verifications: plans start at $49 a month for 10,000 verifications and daily checks on 10 sending domains, every plan includes the API, and unknown results and duplicates are refunded (see pricing).

.NET 8 or newer. Only HttpClient and System.Text.Json from the base library are used, so there are no NuGet packages. Create a project with dotnet new console and replace Program.cs.

Create one HttpClient and reuse it. Creating a new one per call exhausts sockets under load. In an ASP.NET Core app, register a typed client with AddHttpClient and set the base address and bearer header there.

Validate the email format in C# first

.NET gives you two built-in format checks. Use one of them before you spend a credit, because a malformed address can be rejected locally for free.

using System.ComponentModel.DataAnnotations;
using System.Net.Mail;

// Format check 1: MailAddress.TryCreate (.NET 5 and later). It parses an RFC-style address,
// so also compare the parsed Address with the input to reject "Jane <[email protected]>".
static bool LooksLikeEmail(string input) =>
    MailAddress.TryCreate(input, out var parsed) && parsed.Address == input.Trim();

// Format check 2: the [EmailAddress] attribute used by ASP.NET Core model validation.
var attr = new EmailAddressAttribute();
Console.WriteLine(attr.IsValid("a@b"));           // True: one @, not first or last
Console.WriteLine(LooksLikeEmail("[email protected]")); // True
Console.WriteLine(LooksLikeEmail("jane@@acme"));    // False

Know what each one actually does:

CheckWhat it testsCatches a mailbox that doesn't exist?
EmailAddressAttributeNo line breaks, exactly one @, not the first or last characterNo
MailAddress.TryCreateParses the address (and an optional display name); returns false instead of throwingNo
A regexWhatever pattern you wrote; easy to reject valid addresses with + or long TLDsNo
Verification APISyntax, DNS/MX, risk lists, an SMTP mailbox check, a catch-all testYes

The attribute's logic is short enough to read in the .NET runtime source, and TryCreate is documented on Microsoft Learn as available from .NET 5 (both checked 2026-11-22).

Why format checks aren't enough: in Mail Exchange's checks of 779,784 unique business addresses (17 Oct to 22 Nov 2026, mostly B2B contact lists sent through our API), only 100 (about 0.01%) failed syntax. 6,854 (0.9%) were on domains that don't receive mail and 52,136 (6.7%) were rejected by the mail server, 7.6% undeliverable in total, all with a perfectly valid format. Another 18.1% were on catch-all domains, which no format check can see. Those are the addresses that bounce and pause campaigns.

MailAddress.TryCreate and [EmailAddress] would pass every address below the first row. Mail Exchange checks of 779,784 unique business addresses, 17 Oct to 22 Nov 2026 (mostly B2B contact lists).

Verify one address in C#

Save this as Program.cs. It defines a small call helper that sends the key, retries on 429, and turns error responses into an exception or error value with the message from the API. Then verify_one posts the address and handles the one tricky case: a slow mail server.

using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json.Nodes;

var api = new HttpClient
{
    BaseAddress = new Uri("https://mailexchange.com/api/v1/"),
    Timeout = TimeSpan.FromSeconds(45),
};
api.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("MAILEXCHANGE_API_KEY"));

// One API call. Retries 429 with exponential backoff, throws MxException on other errors.
async Task<(HttpStatusCode Status, JsonNode Body)> Call(HttpMethod method, string path, object? body = null)
{
    for (var attempt = 0; ; attempt++)
    {
        using var request = new HttpRequestMessage(method, path);
        if (body is not null) request.Content = JsonContent.Create(body);
        using var response = await api.SendAsync(request);
        if (response.StatusCode == HttpStatusCode.TooManyRequests && attempt < 4)
        {
            await Task.Delay(TimeSpan.FromSeconds(1 << attempt));
            continue;
        }
        var text = await response.Content.ReadAsStringAsync();
        var json = string.IsNullOrWhiteSpace(text) ? new JsonObject() : JsonNode.Parse(text)!;
        if (!response.IsSuccessStatusCode)
            throw new MxException((int)response.StatusCode, (string?)json["error"] ?? text);
        return (response.StatusCode, json);
    }
}

// Turn a result into an action: send, separate, skip, remove or retry.
string Decide(JsonNode result) => ((string?)result["state"], (string?)result["reason"]) switch
{
    ("deliverable", _) => "send",
    ("risky", "low_deliverability") => "separate", // catch-all domain
    ("risky", _) => "skip",                         // role address or disposable
    ("undeliverable", _) => "remove",
    _ => "retry",                                   // unknown, or still pending
};

async Task<JsonNode> VerifyOne(string email)
{
    var (status, body) = await Call(HttpMethod.Post, "verify", new { email });
    if (status != HttpStatusCode.Accepted) return body;

    // 202: the mail server is slow. The check is running and already paid for.
    // Do not post the address again, poll the list instead.
    var listId = (long)body["list_id"]!;
    for (var i = 0; i < 36; i++)
    {
        await Task.Delay(5000);
        var (_, page) = await Call(HttpMethod.Get, $"lists/{listId}/results?limit=1");
        var row = page["results"]!.AsArray().FirstOrDefault();
        if (row is not null && (string?)row["state"] != "pending") return row;
    }
    return body; // still pending after 3 minutes: look again later with the same list_id
}

try
{
    var found = await VerifyOne(args[0]);
    Console.WriteLine($"{(string?)found["email"]} {(string?)found["state"]} {(string?)found["reason"]} -> {Decide(found)}");
}
catch (MxException e)
{
    Console.Error.WriteLine($"Mail Exchange error: {e.Message}");
    return 1;
}
return 0;

class MxException(int status, string message) : Exception($"HTTP {status}: {message}")
{
    public int Status { get; } = status;
}

Run it:

MAILEXCHANGE_API_KEY=mx_live_xxx dotnet run -- [email protected]

Typical output looks like [email protected] deliverable accepted_email -> send.

About the 202. Most checks finish within a few seconds. If a mail server is slow, /verify waits about 20 seconds and then returns 202 with {"state": "pending", "list_id": ...}. That check is already running and was already charged. Posting the same address again would start a second check and charge again, so read the result from /lists/{list_id}/results instead, as the code does. More in errors, credits and rate limits.

Read the result and decide what to do

A result is a flat JSON object: email, state, reason, score, and the flags accept_all, role, free, disposable, plus mx. The state is what you branch on. The reason tells you why, and matters for the risky group. The decide function in the code above maps it like this:

statereasondecide() returnsWhy
deliverableaccepted_emailsendThe mail server accepted the mailbox.
riskylow_deliverabilityseparateCatch-all domain. Cannot be confirmed either way. Send carefully or keep apart.
riskylow_quality, disposableskipRole address (info@, sales@) or a throwaway domain.
undeliverablerejected_email, invalid_domain, invalid_emailremoveWill bounce. Drop it.
unknownunavailable_smtp, no_connect, dns_errorretryThe server did not give a clear answer. The credit is refunded.

A cold email team might send separate addresses only from established inboxes, as described in catch-all emails and cold email. The full list of states is in email verification statuses, and how it works explains the six checks behind them.

The mapping used in both C# examples. Change it to suit your use: a signup form might accept risky addresses and block only undeliverable ones.

Verify a list in C#

For more than a handful of addresses, submit one list instead of looping over /verify. You get a list ID straight away, poll GET /lists/{id} until its status is done (or failed), then page through /lists/{id}/results 1,000 rows at a time. Duplicates inside the list are removed and not charged. Save this as Program.cs with one address per line in emails.txt.

// Same usings, HttpClient setup, Call() helper and Decide() as the first example: paste them here.

async Task<(JsonNode Summary, List<JsonNode> Rows)> VerifyList(string[] addresses)
{
    var created = (await Call(HttpMethod.Post, "lists", new { emails = addresses, name = "csharp-example" })).Body;
    var id = (long)created["id"]!;

    JsonNode current;
    while (true)
    {
        current = (await Call(HttpMethod.Get, $"lists/{id}")).Body;
        var status = (string?)current["status"];
        Console.WriteLine($"{(int)current["checked"]!}/{(int)current["total"]!} checked ({status})");
        if (status is "done" or "failed") break;
        await Task.Delay(5000);
    }
    if ((string?)current["status"] == "failed") throw new InvalidOperationException($"list {id} failed");

    var rows = new List<JsonNode>();
    for (var offset = 0; ; offset += 1000)
    {
        var page = (await Call(HttpMethod.Get, $"lists/{id}/results?offset={offset}&limit=1000"))
            .Body["results"]!.AsArray();
        rows.AddRange(page.Select(n => n!));
        if (page.Count < 1000) break;
    }
    return (current, rows);
}

try
{
    var inputEmails = File.ReadAllLines(args[0]).Select(l => l.Trim()).Where(l => l.Length > 0).ToArray();
    var (list, rows) = await VerifyList(inputEmails);

    Console.WriteLine($"counts: {list["counts"]}");
    foreach (var group in rows.GroupBy(Decide))
        Console.WriteLine($"{group.Key} {group.Count()}");

    await Call(HttpMethod.Delete, $"lists/{(long)list["id"]!}"); // optional: remove the list and its results
}
catch (MxException e)
{
    Console.Error.WriteLine($"Mail Exchange error: {e.Message}");
    return 1;
}
return 0;

// plus the MxException class from the first example
MAILEXCHANGE_API_KEY=mx_live_xxx dotnet run -- emails.txt

Instead of polling you can pass a callback_url and let us call you when the list is done, see webhooks and callbacks. The whole flow, including CSV download and deleting a list, is in verify a list with the API.

Errors, 402 and 429

Every error response is JSON with an error field, which the helper surfaces in the exception message. The ones to plan for:

  • 429 means you hit the per-key rate limit. The helper waits 1, 2, 4 and 8 seconds and tries again, which is safe because a rate-limited request does no work and costs nothing.
  • 402 means you do not have enough credits for the request. Retrying will not help. Stop, alert someone, and upgrade your plan or wait for it to renew. GET /account returns your balance if you want to check first.
  • 401 means the key is missing or wrong. 400 means the request was malformed, for example no email, or a list over 100,000 addresses.

Details and a status code table are in errors, credits and rate limits.

A rate-limited request does no work and costs nothing, so retrying it is safe. A 402 (out of credits) is never retried.

Frequently asked questions

How do I validate an email address in C#?

Use MailAddress.TryCreate (from .NET 5) or the EmailAddressAttribute for the format, then call a verification API to check that the mailbox exists. A format check alone misses addresses on dead domains, rejected mailboxes and catch-all domains, which are the ones that bounce.

Does EmailAddressAttribute check that an email exists?

No. In current .NET it only checks that the value has no line breaks and exactly one @ that is neither the first nor the last character. It never looks up the domain or contacts the mail server.

Is there an official C# SDK for the Mail Exchange API?

No, and none is needed. The API is plain HTTPS and JSON, so the examples on this page use only the standard library.

How do I get an API key?

Create a key in your account dashboard under API keys, after signing up. Send the key as a bearer token in the Authorization header. Checks use your plan's monthly verifications (every plan includes the API), and they reset every month; unused ones don't carry over.

What should I do when /verify returns 202?

Do not send the address again. The check is already running and paid for. Read the result from /lists/{list_id}/results using the list_id in the 202 response, until the state is no longer pending.

Want to try it on real addresses first? The free trial gives you 25 checks in the web app, or paste a single address into the free email checker.

Start your free trial →