TL;DR
- The Mail Exchange API is plain HTTPS and JSON at
https://mailexchange.com/api/v1, no SDK. POST /verifychecks one address and usually answers in a few seconds.POST /listschecks up to 100,000 addresses in the background.- Branch on
state: deliverable, risky, undeliverable or unknown. Handle202(still checking),402(out of credits) and429(slow down) and you are done. - One credit per address, unknowns refunded. Every plan includes the API, from $49 a month for 10,000 verifications.
Adding verification to a Go signup endpoint, or to a worker that cleans lead lists? Below is a two-file program you can run as is, then lift into your own code: a typed helper, a single check that handles slow mail servers, a bulk list check and a signup handler.
Get an API key
Create one in your account after you sign up; the free trial includes 25 checks. Every request sends the key as Authorization: Bearer your_key. Keep it in an environment variable, out of source control.
The shared helper: mx.go
Go 1.18+, standard library only. Run go mod init mxdemo in an empty folder and save this as mx.go. The call function sends the key, retries 429 with backoff (1, 2, 4 and 8 seconds), decodes the JSON into your struct and returns an *APIError for error statuses, for errors.As.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"time"
)
const base = "https://mailexchange.com/api/v1"
// 45 seconds covers the ~20 second wait /verify can take before a 202.
var client = &http.Client{Timeout: 45 * time.Second}
type APIError struct {
Status int
Message string
}
func (e *APIError) Error() string { return fmt.Sprintf("HTTP %d: %s", e.Status, e.Message) }
// Result is one verification result. The fields match the API response.
type Result struct {
Email string `json:"email"`
State string `json:"state"`
Reason string `json:"reason"`
Score float64 `json:"score"`
AcceptAll bool `json:"accept_all"`
Role bool `json:"role"`
Free bool `json:"free"`
Disposable bool `json:"disposable"`
MX string `json:"mx"`
Provider string `json:"provider"` // on list result rows
ListID int `json:"list_id"` // only on a 202 pending response
}
// Summary is what POST /lists and GET /lists/{id} return.
type Summary struct {
ID int `json:"id"`
Status string `json:"status"`
Total int `json:"total"`
Checked int `json:"checked"`
DuplicatesRemoved int `json:"duplicates_removed"`
Counts map[string]int `json:"counts"`
}
// call makes one API request. It retries 429 with exponential backoff and
// returns *APIError for other error statuses. out may be nil.
func call(ctx context.Context, method, path string, in, out any) (int, error) {
var payload []byte
if in != nil {
var err error
if payload, err = json.Marshal(in); err != nil {
return 0, err
}
}
for attempt := 0; ; attempt++ {
req, err := http.NewRequestWithContext(ctx, method, base+path, bytes.NewReader(payload))
if err != nil {
return 0, err
}
req.Header.Set("Authorization", "Bearer "+os.Getenv("MAILEXCHANGE_API_KEY"))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return 0, err
}
raw, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
return resp.StatusCode, err
}
if resp.StatusCode == http.StatusTooManyRequests && attempt < 4 {
time.Sleep(time.Duration(1<<attempt) * time.Second)
continue
}
if resp.StatusCode >= 400 {
var e struct {
Error string `json:"error"`
}
_ = json.Unmarshal(raw, &e)
if e.Error == "" {
e.Error = string(raw)
}
return resp.StatusCode, &APIError{resp.StatusCode, e.Error}
}
if out != nil {
if err := json.Unmarshal(raw, out); err != nil {
return resp.StatusCode, err
}
}
return resp.StatusCode, nil
}
}
// decide turns a result into an action: send, separate, skip, remove or retry.
func decide(r Result) string {
switch r.State {
case "deliverable":
return "send"
case "risky":
if r.Reason == "low_deliverability" { // catch-all domain
return "separate"
}
return "skip" // role address or disposable
case "undeliverable":
return "remove"
}
return "retry" // unknown, or still pending
}
Verify one address in Go
Save this as main.go next to mx.go. verifyOne handles the tricky case, a slow mail server; main runs a single check or a list.
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"time"
)
func verifyOne(ctx context.Context, email string) (Result, error) {
var r Result
status, err := call(ctx, "POST", "/verify", map[string]string{"email": email}, &r)
if err != nil || status != http.StatusAccepted {
return r, err
}
// 202: the check is running and already paid for. Never post the address again.
for i := 0; i < 36; i++ {
time.Sleep(5 * time.Second)
var page struct {
Results []Result `json:"results"`
}
if _, err := call(ctx, "GET", fmt.Sprintf("/lists/%d/results?limit=1", r.ListID), nil, &page); err != nil {
return r, err
}
if len(page.Results) > 0 && page.Results[0].State != "pending" {
return page.Results[0], nil
}
}
return r, nil // still pending after 3 minutes: look again later with r.ListID
}
func verifyList(ctx context.Context, emails []string) (Summary, []Result, error) {
var s Summary
if _, err := call(ctx, "POST", "/lists", map[string]any{"emails": emails, "name": "go-example"}, &s); err != nil {
return s, nil, err
}
id := s.ID
for s.Status != "done" && s.Status != "failed" {
time.Sleep(5 * time.Second)
if _, err := call(ctx, "GET", fmt.Sprintf("/lists/%d", id), nil, &s); err != nil {
return s, nil, err
}
fmt.Printf("%d/%d checked (%s)\n", s.Checked, s.Total, s.Status)
}
if s.Status == "failed" {
return s, nil, fmt.Errorf("list %d failed", id)
}
var all []Result
for offset := 0; ; offset += 1000 {
var page struct {
Results []Result `json:"results"`
}
path := fmt.Sprintf("/lists/%d/results?offset=%d&limit=1000", id, offset)
if _, err := call(ctx, "GET", path, nil, &page); err != nil {
return s, nil, err
}
all = append(all, page.Results...)
if len(page.Results) < 1000 {
break
}
}
return s, all, nil
}
func main() {
if len(os.Args) < 3 || (os.Args[1] != "one" && os.Args[1] != "list") {
fmt.Fprintln(os.Stderr, "usage: go run . one [email protected] | go run . list [email protected] [email protected] ...")
os.Exit(2)
}
ctx := context.Background()
var err error
if os.Args[1] == "one" {
var res Result
if res, err = verifyOne(ctx, os.Args[2]); err == nil {
fmt.Println(res.Email, res.State, res.Reason, "->", decide(res))
}
} else {
var s Summary
var results []Result
if s, results, err = verifyList(ctx, os.Args[2:]); err == nil {
actions := map[string]int{}
for _, r := range results {
actions[decide(r)]++
}
fmt.Println("counts:", s.Counts, "duplicates removed:", s.DuplicatesRemoved, "actions:", actions)
_, _ = call(ctx, "DELETE", fmt.Sprintf("/lists/%d", s.ID), nil, nil) // optional cleanup
}
}
var apiErr *APIError
if errors.As(err, &apiErr) && apiErr.Status == http.StatusPaymentRequired {
fmt.Fprintln(os.Stderr, "out of credits, upgrade the plan and run again:", apiErr.Message)
os.Exit(1)
} else if err != nil {
fmt.Fprintln(os.Stderr, "Mail Exchange error:", err)
os.Exit(1)
}
}
export MAILEXCHANGE_API_KEY=mx_live_xxx
go run . one [email protected]
# [email protected] deliverable accepted_email -> send
/verify waits about 20 seconds, then returns 202 with {"state": "pending", "list_id": ...}. The check is running and charged; posting again would charge twice, so read /lists/{list_id}/results as the code does.Read the result and decide what to do
A result is a flat JSON object: email, state, reason, score, the flags accept_all, role, free, disposable, and mx. Branch on state; reason tells you why, which matters for the risky group. decide maps it like this:
| state | reason | decide() returns | Why |
|---|---|---|---|
| deliverable | accepted_email | send | The mail server accepted the mailbox. |
| risky | low_deliverability | separate | Catch-all domain: accepts every address, so the mailbox cannot be confirmed. |
| risky | low_quality, disposable | skip | Role address (info@, sales@) or a throwaway domain. |
| undeliverable | rejected_email, invalid_domain, invalid_email | remove | Will hard bounce. |
| unknown | unavailable_smtp, no_connect, dns_error | retry | No clear answer from the server. The credit is refunded. |
Change it to fit your use: a cold email team might send separate addresses only from established inboxes (catch-all emails and cold email). All states are in email verification statuses, and how it works explains the six checks behind them.
Verify a list in Go
For more than a handful of addresses, use verifyList instead of a loop of goroutines calling /verify. One POST /lists takes up to 100,000 addresses and counts against a much larger rate-limit allowance. You get a list ID straight away, poll GET /lists/{id} every 5 seconds until status is done or failed, then page through the results 1,000 rows at a time.
go run . list [email protected] [email protected] [email protected]
# counts: map[deliverable:1 risky:0 undeliverable:1 unknown:0] duplicates removed: 1 actions: map[remove:1 send:1]
What to expect from a real list: in Mail Exchange's checks of 779,784 unique business addresses across 200,799 domains (17 Oct to 22 Nov 2026, mostly B2B contact lists, not a random sample of all email), 18.1% were catch-all, 7.8% role addresses and 7.6% undeliverable. The rest came back deliverable or unknown, and unknown results are refunded. To skip polling, pass a callback_url and handle the signed list.done event (webhooks and callbacks); CSV download and deleting are covered in verify a list with the API.
Use it in a signup handler
In a handler, don't wait minutes: call /verify once, treat 202 as "check later", and never block a signup because verification itself failed. This fragment reuses call and Result from mx.go (add "log" to the imports; createAccount stands for your own code):
func signupHandler(w http.ResponseWriter, r *http.Request) {
email := r.FormValue("email")
var res Result
status, err := call(r.Context(), "POST", "/verify", map[string]string{"email": email}, &res)
switch {
case err != nil:
log.Println("verification unavailable:", err) // 402, repeated 429 or network
createAccount(email, "unverified")
case status == http.StatusAccepted:
createAccount(email, "pending") // store res.ListID and read the result later
case res.State == "undeliverable":
http.Error(w, "That address can't receive email. Please check it.", http.StatusUnprocessableEntity)
case res.Disposable:
http.Error(w, "Please use a permanent email address.", http.StatusUnprocessableEntity)
default:
createAccount(email, res.State) // deliverable, catch-all, role or unknown
}
}
The worst case is the roughly 20 seconds before a 202. A shorter context deadline still gets the check charged but loses the list_id, so prefer the full wait. Accepting catch-all addresses is deliberate: in our data above, 51.9% of the Google Workspace domains where the catch-all test reached a verdict accepted any address, so rejecting risky would turn away real buyers (is Google Workspace a catch-all?).
Errors, 402 and 429
Errors are JSON with an error field, which call puts in APIError.Message. Match on Status:
- 429: per-key rate limit over a rolling 60-second window.
callwaits 1, 2, 4 and 8 seconds and tries again; a rate-limited request costs nothing. - 402: not enough credits. Retrying will not help, and nothing was created or charged. Stop, alert someone and upgrade your plan or wait for it to renew.
GET /accountreturns your balance. - 401: key missing or wrong. 400: malformed request, such as no
emailor a list over 100,000 addresses. 404: unknown list ID. - Network errors and 5xx: retry with backoff, but after a timeout on a submit check
GET /accountbefore resubmitting.
The full status table is in errors, credits and rate limits.
Questions
Is there an official Go 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?
Sign up, then create a key in your account under API keys; the free trial includes 25 checks. 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.
Should I loop over /verify for a big list in Go?
No. Submit one POST /lists call with up to 100,000 addresses. It counts against a much larger rate-limit allowance, removes duplicates for free and runs in the background, so you do not need a pool of goroutines holding connections open.
Related
- Email verification API reference
- Verify a list with the API and webhooks and callbacks
- Errors, credits and rate limits
- Same examples in Python, Node.js, PHP, Ruby, Java and C#
- Pricing and all developer guides
