Article

How to Check MX Records Programmatically: Working Code and Verdict Logic

By Unlimited Verifier Team ·

Flow diagram showing an email domain sent through an MX DNS query and sorted into valid hosts, no MX, invalid domain, or retry outcomes.

Summary

To check MX records programmatically, send an MX-type DNS query for the email's domain, sort the answers by preference, and treat the domain as mail-capable only if a usable host is returned. Node.js, Go and PHP support this with built-in resolvers, while Python needs the dnspython package. A DNS check confirms a domain can receive mail, but it does not confirm that a specific mailbox exists.

To check MX records programmatically, send a DNS query of type MX for the email's domain, sort the answers by preference (lowest number first), and mark the domain mail-capable only if a usable host comes back. Node.js, Go and PHP do this with built-in resolvers, while Python needs the dnspython package.

This DNS step is the cheapest layer of real-time email validation, and it is the layer most often misread. An MX record shows where mail for a domain should be delivered. It does not prove that a particular mailbox exists. This guide covers working code, a verdict table for every DNS answer, a batch workflow for large lists, a worked cost example, and the point where a DNS-only check stops being enough.

Quick answer

What does an MX lookup actually tell you?

An MX lookup returns the hosts that accept mail for a domain, ranked by preference. It shows the domain is set up to receive email. It does not show that jane@ exists on that domain.

Each MX record has two fields. Preference is a number where lower values are tried first. Exchange is the hostname that accepts mail. A typical answer is 10 mx1.mail-provider.example. plus 20 mx2.mail-provider.example., meaning senders try the first host and fall back to the second.

Three edge cases catch people out:

Bottom line: An MX answer proves the domain is configured for mail. It does not prove the mailbox exists, and "no MX" needs a follow-up check.

How do you query MX records in code?

Use your language's resolver with an explicit MX query type, and set a timeout you control. The Node.js example uses the built-in dns module, and the Python example uses dnspython.

Node.js (built in)

import { promises as dns } from 'node:dns';

// A resolver with explicit limits, so one slow nameserver can't stall a batch
const resolver = new dns.Resolver({ timeout: 5000, tries: 2 });

export async function checkMx(domain) {
  try {
    const records = await resolver.resolveMx(domain);
    const hosts = records
      .map(r => ({ priority: r.priority, host: r.exchange.replace(/\.$/, '') }))
      .filter(r => r.host !== '')
      .sort((a, b) => a.priority - b.priority);
    return hosts.length ? { status: 'mx', hosts } : { status: 'null-mx' };
  } catch (err) {
    if (err.code === 'ENOTFOUND') return { status: 'no-domain' };
    if (err.code === 'ENODATA') return { status: 'no-mx' };
    return { status: 'temporary-error', code: err.code };
  }
}

Python (dnspython)

import dns.resolver
import dns.exception

def check_mx(domain: str, timeout: float = 5.0) -> dict:
    resolver = dns.resolver.Resolver()
    resolver.lifetime = timeout  # total time budget for the query
    try:
        answers = resolver.resolve(domain, "MX")
    except dns.resolver.NXDOMAIN:
        return {"status": "no-domain"}
    except dns.resolver.NoAnswer:
        return {"status": "no-mx"}
    except (dns.resolver.NoNameservers, dns.exception.Timeout):
        return {"status": "temporary-error"}
    except dns.exception.SyntaxError:
        return {"status": "bad-domain"}
    hosts = sorted((r.preference, str(r.exchange).rstrip(".")) for r in answers)
    hosts = [(p, h) for p, h in hosts if h]
    return {"status": "mx", "hosts": hosts} if hosts else {"status": "null-mx"}
Language Call Outcomes to handle Practical notes
Node.js dns.promises.Resolver, then resolveMx ENOTFOUND, ENODATA, other codes Built in. The timeout and tries options set limits. Node.js DNS docs
Python dnspython, then resolve(d, "MX") NXDOMAIN, NoAnswer, NoNameservers, Timeout, SyntaxError Third-party package. lifetime caps total query time. dnspython
Go net.DefaultResolver.LookupMX(ctx, d) *net.DNSError with IsNotFound Standard library. The context sets the deadline. Results come back sorted by preference. net package
PHP dns_get_record($d, DNS_MX) Empty array or false Built in. Returns target and pri keys. No per-call timeout, so the system resolver sets it. PHP manual
Shell (spot checks) dig MX example.com status: NXDOMAIN in the header Good for one-off checks. Don't call it in a loop.

Run this check on the server. Browsers can't issue DNS queries, so front-end code can only check syntax. Client-side vs server-side validation explains the split. If you use React Hook Form, keep format rules on the client and send the MX check to your API. For language-specific guides, see JavaScript, TypeScript, Laravel's DNS rule, Go packages and Spring Boot.

Bottom line: Use an explicit MX query type in every language, and set a timeout you control.

How do you turn MX answers into a verdict?

Map each DNS result to one action. The table below shows the decision logic.

Resolver result What it means Correct action
MX hosts with real exchanges Domain accepts mail Pass. Run an SMTP mailbox check if your workflow includes one.
Null MX (preference 0, exchange .) Domain explicitly accepts no mail Mark Invalid and suppress.
No MX, but A or AAAA exists Implicit MX under RFC 5321 Don't reject. Send to the mailbox check.
No MX and no A or AAAA No route for mail Mark Invalid.
NXDOMAIN (no such domain) Domain doesn't exist Mark Invalid.
Malformed domain (syntax error) Not a valid domain string Mark Invalid. Reject before querying if you can.
Timeout or SERVFAIL Resolver failure, not an answer Retry later and hold the row. Don't mark Invalid.

The code above returns no-mx for both middle rows, so run a follow-up A or AAAA query on those domains before deciding.

Invalid verdicts should rest on four results: null MX, nonexistent domains, malformed domains, and domains with no mail route at all. Timeouts go to a retry queue. Teams that treat timeouts as failures delete valid contacts during a DNS outage.

Cache verdicts for one batch job, or a few hours for signup traffic. Don't cache for days. Domain owners change mail providers, and a stale answer can flag a working domain.

A DNS result also has a limit. A catch-all server accepts any local part, so MX records can't tell you whether jane@ exists. Catch-all email verification covers that layer.

Bottom line: Invalid verdicts rest on four DNS results, and timeouts are not among them.

How do you check MX records at scale, step by step?

A reliable batch checker follows seven steps, and each one prevents a specific error.

  1. Extract the domain safely. Split on the last @, because a quoted local part can contain @. Trim whitespace, lowercase the result, and reject strings without @ before any query.
  2. Convert internationalised domains to ASCII. bücher.de must be queried as xn--bcher-kva.de. In Python, .encode("idna") does this and raises UnicodeError on failure.
  3. Deduplicate by domain. Lists reuse a small set of providers, so one lookup per unique domain covers the whole file.
  4. Set timeouts and concurrency. Start with 5-second timeouts and 20 to 50 concurrent lookups, then tune against your resolver.
  5. Classify each answer with the verdict table above.
  6. Retry temporary errors once or twice with a short backoff. Rows that still fail go to a hold bucket, never to Invalid.
  7. Store each result with a timestamp. An undated verdict can't be audited or re-run later.

Bottom line: Steps 1 to 3 (extraction, IDNA conversion and deduplication) remove most wasted lookups and most false results.

How do you check a CSV of addresses in Python?

This tutorial checks every domain in a CSV and writes one verdict per row. It takes about ten minutes with Python 3.

  1. Install the package. Run pip install dnspython.
  2. Save the function. Put the Python check_mx function from above in a file named mx_check.py.
  3. Prepare your file. Create contacts.csv with a header row that includes an email column, for example:
email
jane@example.com
ops@no-such-domain.invalid
  1. Save the batch script as run_mx_check.py in the same folder:
import csv
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
from mx_check import check_mx

def email_of(row: dict) -> str:
    return (row.get("email") or "").strip()

def domain_of(email: str) -> str:
    if "@" not in email:
        return ""
    return email.rsplit("@", 1)[-1].strip().lower()

with open("contacts.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.DictReader(f))

domains = sorted({domain_of(email_of(r)) for r in rows} - {""})

with ThreadPoolExecutor(max_workers=40) as pool:
    verdicts = dict(zip(domains, pool.map(check_mx, domains)))

with open("results.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["email", "domain", "mx_status"])
    for r in rows:
        email = email_of(r)
        d = domain_of(email)
        if not d:
            writer.writerow([email, "", "malformed"])
        else:
            writer.writerow([email, d, verdicts[d]["status"]])

print(Counter(v["status"] for v in verdicts.values()))
  1. Run it with python run_mx_check.py. The final line prints a count per status.
  2. Act on the output. Suppress no-domain, null-mx, bad-domain and malformed rows. Run an A lookup on no-mx rows before deciding. Requeue temporary-error rows for a rerun.

This script checks DNS only. It doesn't confirm individual mailboxes. SMTP probes need outbound port 25, which many hosts block. Why SMTP verification gets blocked explains the common failure modes.

Bottom line: The script is short. The value lies in the classification and the rerun logic around it.

How much does a 50,000-row MX check cost and take?

The figures below are illustrative. The timings and domain counts are assumptions, but the plan limits are real. Take a SaaS sales team importing 50,000 prospect rows, a typical email verification for ecommerce and SaaS case.

Step 1: Deduplicate. Assume the list has 6,500 unique domains. Deduplication removes 43,500 lookups, which is 87% of the 50,000 queries.

Step 2: Estimate time. Assume a 60 ms average lookup and 40 concurrent workers.

That cuts DNS time by 87%. Real runs are slower because of retries and resolver variance, so the ratio matters more than the exact figures.

Step 3: Classify the 6,500 domains (illustrative).

Check the total: 5,850 + 350 + 50 + 120 + 127 + 3 = 6,500. Every row on the 170 Invalid domains is Invalid. The 3 held domains are not marked Invalid.

Step 4: Decide where DNS ends. A DNS pass can't confirm mailboxes, catch-all behaviour, or disposable and role-based addresses. Here is how the plan limits work for those checks on Unlimited Verifier:

Upload and verify a list to run the batch. Results are kept 24 hours on Free and 30 days on Pro, so export them as CSV, Excel or JSON when the job finishes. For how verification vendors structure their costs, see email verification pricing.

For prospect lists in particular, the workflow in email verification for sales prospecting covers how to prioritise which rows to verify first.

Bottom line: In this illustration, deduplication removed 87% of the lookups. The mailbox step is where a verification service adds value.

Should you build this yourself or call an API?

Building the DNS layer yourself is reasonable, but it covers only the first slice of the job. The table compares the options.

Option What it checks Cost model Where it breaks Best fit
DIY DNS-only MX check MX, A, NXDOMAIN, null MX Your compute and resolver traffic Can't confirm mailboxes, catch-all domains or disposable addresses Signup pre-filter and domain triage
DIY MX plus SMTP probe MX plus mailbox response Your compute, IP reputation and port 25 access Many cloud providers restrict port 25, and greylisting can delay probes Teams with spare engineering time and clean sending IPs
Unlimited Verifier upload Syntax, domain and MX, SMTP mailbox, catch-all, disposable, role-based Unlimited standard verification on every plan Files up to 10MB. No native CRM, ESP or Zapier integrations, so export and re-import Large one-off and recurring list cleans
Email verification API The same checks, one address or up to 10,000 per request Pro includes 100,000 API emails a month. No API on Free You handle pacing and retries in your own code Signup forms and data pipelines

If you're weighing vendors, the best email verification tools compare on categories, checks and workflow fit. Unlimited Verifier sorts every address into Valid, Risky or Invalid, and it flags catch-all, disposable and role-based addresses. Those flags matter because a clean MX record doesn't separate a real person from a shared inbox such as info@. For workflow patterns with an API, see email verification API and automation. For signup forms, see real-time verification at signup.

Unlimited Verifier publishes its verification engine as open source on GitHub, so you can read how the checks are implemented. Use the free single-email checker to spot-check one address before committing to a batch.

Bottom line: Use DNS-only checks for cheap triage. Use a full verification service when the decision affects who receives mail.

How do you avoid throttling and blocks at scale?

Most throttling and blocking comes from three sources: too many simultaneous queries, retries without backoff, and blocked outbound ports.

Bottom line: Most large runs fail because of concurrency and timeouts, not because of the list.

What mistakes break MX checks?

Bottom line: Most errors come from treating DNS answers as more certain than they are.

How we compared (and limitations)

This guide is based on public documentation: the Node.js dns docs, the dnspython documentation, the Go net package docs, the PHP manual, and RFCs 5321 and 7505. We haven't benchmarked these libraries against each other or run the code against live domain sets for this article.

The 75-second and 9.75-second timings and the domain breakdown are illustrative assumptions. The concurrency and timeout values (40 workers, 5 seconds, one retry) are starting points, not standards. Tune them against your own resolver and network.

Unlimited Verifier details come from its published plan information. The 99.5% accuracy figure is the company's stated accuracy for deep verification, not an independent benchmark. Plan limits and prices can change, so check the current plan page before running a large job.

Bottom line: Treat the code as a starting point, and test it against your own domains before relying on it for a large send.

MX answer verdict table

DNS answer Verdict Action
MX hosts returned (non-null) Mail-capable Accept domain, continue checks
Null MX (pref 0, exchange '.') Does not accept mail Reject address
No MX, A/AAAA exists Possible mail via fallback Flag for follow-up check
No MX, no A/AAAA Not mail-capable Reject address
NXDOMAIN Domain does not exist Reject address
SERVFAIL or timeout Temporary failure Retry with backoff, then mark unknown

Frequently asked questions

Why does dns.lookup not return MX records?

dns.lookup and similar hostname calls return A or AAAA addresses, not MX records. To get mail exchangers, you must use an explicit MX query such as Node's resolveMx or dnspython's resolve with type MX.

What does a null MX record mean?

A null MX record uses preference 0 and exchange '.' and is defined in RFC 7505. It explicitly states the domain accepts no mail, so your code should mark that domain as not mail-capable.

Should I reject a domain that has no MX record?

Not automatically. RFC 5321 section 5.1 lets senders fall back to the domain's A or AAAA record when no MX exists, so a missing MX should trigger a follow-up address check rather than a rejection.

How long should my MX lookup timeout be?

A common starting point is about 5 seconds with one retry for temporary failures. This is a practical default rather than a published standard, so tune it against your own resolver's behavior.

Do I need to query MX for every email address?

No. Deduplicate by domain first, since large lists often contain far fewer unique domains than addresses. Cache results for the TTL the resolver returns.

Which MX host should I use if there are several?

Sort by preference, lowest number first. Among hosts with equal preference, RFC 5321 says to choose in random order, so the listed order between them has no meaning.

Can an MX check confirm a mailbox exists?

No. An MX check only shows the domain is set up to receive mail. Confirming a specific mailbox requires an SMTP-level or other mailbox-level verification step, which carries its own deliverability and policy considerations.

What is the difference between NXDOMAIN and no MX?

NXDOMAIN means the domain itself does not exist, so the address is almost certainly invalid. No MX means the domain exists but publishes no mail exchanger, which calls for an A or AAAA fallback check.

Why do I get SERVFAIL or timeouts on some domains?

These are temporary resolver or nameserver problems. Retry them with backoff and avoid marking the address invalid on the first failure.

Cut Bounces and Protect Your Sender Reputation With Unlimited Email Verification

Every invalid address you send to hurts your sender reputation and your inbox placement. Verifying your list before each send means fewer bounces, healthier deliverability, and a predictable cost. With Unlimited Verifier, standard verification is unlimited on every plan, with no per-email fees.

Unlimited Verifier checks syntax, domain, MX records and the SMTP mailbox. It also detects catch-all domains and flags disposable and role-based addresses. Export a CSV from your email platform or CRM, upload and verify the list, then re-import the clean results. You can also automate checks with the email verification API.

Free Pro
Price $0 $29/month ($25/month billed annually)
Lists 25 a month, up to 150 emails each Unlimited, up to 25,000 emails each
Deep verifications 750 a month 25,000 a month
API access No Yes (100,000 emails a month)
Result retention 24 hours 30 days

Why teams choose Unlimited Verifier

Unlimited Verifier states 99.5% accuracy for deep verification.

Create a free account and verify your next list before you hit send.

Want to test a single address first? Try the free email checker.