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-10-18

TL;DR

  • 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

Keys are issued on request. Ask for one and we will set you up with free test credits. 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. Credit prices are on the pricing page and credits never expire.

What you need

.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. The examples use top-level statements and the console template's implicit usings (System.Linq, System.IO), which are on by default in .NET 8 projects.

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.

The function is deliberately small so you can change it. A cold email team might send separate addresses only from established inboxes, as described in catch-all emails and cold email. A signup form might accept risky addresses but block undeliverable ones. The full list of states is in email verification statuses, and how it works explains the six checks behind them.

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.

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 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;

class MxException(int status, string message) : Exception($"HTTP {status}: {message}")
{
    public int Status { get; } = status;
}
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 top up. 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.

Questions

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?

Keys are issued on request through the contact page, and they come with free test credits. Send the key as a bearer token in the Authorization header.

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.

Related