Engineering

MX Record Lookup API: Check Mail Servers and Email Routing in JSON

Query MX records programmatically, interpret mail server priority, verify provider migrations, and detect missing or unexpected inbound email routing.

June 8, 202610 min readEngineering · DNS · Email Routing · MX

Introduction

Email routing errors are easy to miss and expensive to debug. A stale MX record can keep messages flowing to an old provider, while a missing MX record can silently break inbound email for a customer domain. An MX record lookup API turns those checks into structured JSON your application can compare, monitor, and audit.

WhoisJSON does not require a separate MX-only endpoint. Use the DNS Lookup API /nslookup endpoint and read the MX array from the response. Each MX object contains the mail server hostname in exchange and its routing preference in priority.

What Is an MX Record Lookup API?

An MX record lookup API accepts a domain name, queries its DNS configuration, and returns the mail exchange records as JSON. Your application can identify the preferred mail server, list fallback servers, compare the result with an expected provider, or flag domains that publish no MX records.

Endpoint used in this guide: GET /api/v1/nslookup?domain=example.com. WhoisJSON returns all available DNS record types in one response. Read the MX array for mail routing.

This is a focused MX workflow built on the broader DNS endpoint. For A, AAAA, CNAME, NS, SOA, TXT, CAA, DMARC, BIMI, MTA-STS, and TLS-RPT records, see the complete DNS Lookup API guide.

How MX Records Route Incoming Email

Each MX record combines a priority number with a mail server hostname. Sending systems try the lowest numerical priority first. If that server cannot accept the message, they can try records with higher numbers.

Example DNS recordsDNS
example.com. 3600 IN MX 10 mail1.example.net.
example.com. 3600 IN MX 20 mail2.example.net.
ValueMeaningRouting behavior
10 mail1.example.netPrimary mail exchanger.Tried before the priority 20 server.
20 mail2.example.netFallback mail exchanger.Used when the preferred route is unavailable.
Same priority on multiple recordsEquivalent preference.Sending systems may distribute attempts across them.
Lower numbers have higher preference. Priority 10 is attempted before priority 20. The number is an ordering value, not a quality or security score.

Query MX Records in JSON

Send the root domain in the domain query parameter and authenticate with Authorization: TOKEN=YOUR_API_KEY.

RequestcURL
curl "https://whoisjson.com/api/v1/nslookup?domain=example.com" \
  -H "Authorization: TOKEN=YOUR_API_KEY"

The documented MX response contains an array of objects. Each object exposes only the exchange hostname and priority, so integrations should not assume that TTL, SMTP status, or mailbox validation is present.

Response shapeJSON
{
  "MX": [
    {
      "exchange": "mail1.example.net",
      "priority": 10
    },
    {
      "exchange": "mail2.example.net",
      "priority": 20
    }
  ]
}

How to Interpret MX Lookup Results

The correct result depends on the domain's role and expected mail provider. Use an allowlist or baseline when you know what should be deployed.

No MX records

The domain has no explicit inbound mail route. That may be intentional for a web-only domain, but it is a problem for a domain expected to receive email.

One provider, several records

Normal for hosted email platforms that publish multiple preferred and fallback servers for resilience.

Old and new providers mixed

Often indicates an incomplete migration. Confirm whether the old route should still receive mail before removing it.

Unexpected exchange

Treat as configuration drift. Compare it with change records and verify control of the DNS account before escalating.

MX records describe inbound routing, not sender authentication. Use the DMARC lookup API guide for policy enforcement and inspect TXT records for SPF context.

Python Example: Check Mail Servers

This example sorts MX records by priority and compares their hostnames with an expected provider suffix.

mx_lookup.pyPython
import requests

API_KEY = "YOUR_API_KEY"
BASE_URL = "https://whoisjson.com/api/v1"


def check_mx(domain: str, expected_suffix: str | None = None) -> dict:
    response = requests.get(
        f"{BASE_URL}/nslookup",
        headers={"Authorization": f"TOKEN={API_KEY}"},
        params={"domain": domain},
        timeout=10,
    )
    response.raise_for_status()
    data = response.json()

    records = sorted(
        data.get("MX") or [],
        key=lambda record: record.get("priority", 65535),
    )
    exchanges = [
        record.get("exchange", "").rstrip(".").lower()
        for record in records
    ]

    return {
        "domain": domain,
        "hasMx": bool(records),
        "primary": records[0] if records else None,
        "records": records,
        "expectedProviderFound": (
            any(host.endswith(expected_suffix.lower()) for host in exchanges)
            if expected_suffix else None
        ),
    }


print(check_mx("example.com", "example.net"))

A production integration should handle HTTP 429 and transient 5xx responses with bounded retries and backoff. Do not retry a successful response simply because the MX array is empty.

Node.js Example: Verify an Email Provider

mx-lookup.jsNode.js
const API_KEY = "YOUR_API_KEY";
const BASE_URL = "https://whoisjson.com/api/v1";

async function checkMx(domain, expectedSuffix) {
  const url = new URL(`${BASE_URL}/nslookup`);
  url.searchParams.set("domain", domain);

  const response = await fetch(url, {
    headers: { Authorization: `TOKEN=${API_KEY}` },
  });
  if (!response.ok) {
    throw new Error(`DNS lookup failed: ${response.status}`);
  }

  const data = await response.json();
  const records = [...(data.MX ?? [])].sort(
    (a, b) => (a.priority ?? 65535) - (b.priority ?? 65535)
  );
  const exchanges = records.map(
    ({ exchange }) => exchange.replace(/\.$/, "").toLowerCase()
  );

  return {
    domain,
    hasMx: records.length > 0,
    primary: records[0] ?? null,
    records,
    expectedProviderFound: expectedSuffix
      ? exchanges.some((host) =>
          host.endsWith(expectedSuffix.toLowerCase())
        )
      : null,
  };
}

checkMx("example.com", "example.net")
  .then(console.log)
  .catch(console.error);

Common MX Lookup API Use Cases

  • Email provider migration: confirm that new MX records are active and old provider routes no longer appear.
  • Customer-domain onboarding: verify that a domain expected to receive email publishes at least one inbound route before enabling mail-dependent features.
  • Domain portfolio audits: identify business domains with missing MX records or infrastructure that differs from the approved provider baseline.
  • Vendor review: record the vendor's mail provider and combine it with DMARC, SPF, MTA-STS, TLS-RPT, WHOIS, and SSL signals.
  • Signup risk context: treat missing MX as one contextual signal when a user claims to represent a business domain, never as a standalone fraud verdict.

Bulk MX Audits for Domain Portfolios

The API returns all DNS types in one request per domain, so a bulk MX audit can also collect DMARC, TXT, MTA-STS, and TLS-RPT without additional DNS calls. Use controlled concurrency, preserve failures per domain, and store the previous MX array for change detection.

CheckSuggested result
MX records presentPass, fail, or not applicable based on domain purpose.
Expected provider foundCompare normalized exchange suffixes with an approved list.
Primary route changedReview when the lowest-priority exchange differs from the baseline.
Legacy route remainsFlag after the planned migration window closes.

For reliable concurrency, retry, and backoff patterns, see the API rate limits and retries guide.

What an MX Lookup Cannot Prove

It does not validate a mailbox. An MX record can exist even when a specific address is invalid.
It does not perform an SMTP handshake. The documented endpoint queries DNS and does not connect to the receiving mail server.
It does not guarantee deliverability. Reputation, message content, authentication, recipient policy, and server availability still affect delivery.
It does not prove a domain is legitimate. Malicious domains can configure professional-looking MX records. Combine MX with WHOIS age, DMARC, SSL, and behavioral context.

FAQ

What is an MX record lookup API?

It queries the DNS mail exchange records for a domain and returns the mail server hostnames and their priorities as structured data.

Which WhoisJSON endpoint returns MX records?

Use GET /api/v1/nslookup with the domain query parameter. Read the MX array from the JSON response.

What does MX priority mean?

Lower numbers have higher preference. A server with priority 10 is normally attempted before one with priority 20.

Does an MX record prove that an email address exists?

No. It shows that the domain publishes an inbound mail route. It does not validate a specific mailbox or perform an SMTP check.

Can I check MX and DMARC in one request?

Yes. The /nslookup response can include MX, TXT, DMARC, BIMI, MTASTS, TLSRPT, and standard DNS records in the same response.

Conclusion

An MX record lookup API turns inbound email routing into structured data that applications can compare, monitor, and audit. Read exchange and priority from the MX array, sort lower priorities first, and compare the result with the domain's expected provider.

Keep the conclusion narrow: MX records reveal routing, not mailbox validity or guaranteed deliverability. For a stronger email-domain assessment, combine them with DMARC and TXT records from the same DNS response plus WHOIS and SSL context.

Check MX records with WhoisJSON

Query MX, DMARC, TXT, MTA-STS, TLS-RPT, and standard DNS records with one API key.

Check MX RecordsView Documentation
Email Routing

Audit Mail Routing in One API Call

Query MX priorities together with DMARC, TXT, MTA-STS, TLS-RPT, and standard DNS records.

MX exchange and priorityPython and Node.jsFull DNS response1,000 free requests/month