How to validate email addresses in Rust

Build an async email validator in Rust step by step: syntax checks, MX lookups with hickory-resolver, disposable-domain detection, typo suggestions and an axum sign-up handler.

What we'll build

A regular expression can tell you an address looks right. It can't tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build an EmailValidator in Rust whose async validate() method checks all of those and returns one of four statuses:

StatusMeaningTypical action
validWell formed, and the domain accepts mailAccept
invalidBad syntax, no such domain, or no mail serverReject and ask the user to fix it
riskyDisposable, a likely typo, a role account, or no MX recordsYour call: block, warn, or flag
unknownDNS failed temporarilyAccept and check again later

You'll need Rust 1.88 or later (the code uses edition 2024). Add hickory-resolver for DNS lookups, idna for international domain names and tokio, plus axum and serde for the sign-up handler in step 7:

cargo add hickory-resolver idna serde_json
cargo add tokio --features full
cargo add serde --features derive
cargo add axum

Every snippet was tested with Rust 1.97, hickory-resolver 0.26 and axum 0.8, and passes Clippy. Want to see the end result first? The free email checker runs the same checks.

1. Check the syntax

Start with the check that needs no network. Instead of a regular expression, split the address at the last @ and check each part with plain character tests. An enum for the result means the compiler won't let you use the domain without checking it first:

src/syntax.rs
/// The parts of a well-formed address, or the reason it isn't one.
#[derive(Debug, PartialEq)]
pub enum Syntax {
    Ok {
        local: String,
        domain: String,
        normalized: String,
    },
    Invalid(&'static str),
}

/// RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
fn is_atom(part: &str) -> bool {
    !part.is_empty()
        && part
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || "!#$%&'*+/=?^_`{|}~-".contains(c))
}

/// A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
fn is_label(label: &str) -> bool {
    (1..=63).contains(&label.len())
        && !label.starts_with('-')
        && !label.ends_with('-')
        && label
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
}

pub fn check_syntax(input: &str) -> Syntax {
    let email = input.trim();
    if email.len() > 254 {
        return Syntax::Invalid("too_long");
    }
    let Some((local, raw_domain)) = email.rsplit_once('@') else {
        return Syntax::Invalid("missing_at_or_part");
    };
    if local.is_empty() || raw_domain.is_empty() {
        return Syntax::Invalid("missing_at_or_part");
    }
    if local.len() > 64 {
        // len() counts bytes, which is what RFC 5321 limits
        return Syntax::Invalid("local_part_too_long");
    }
    // split() keeps empty parts, so leading, trailing and doubled dots fail.
    if !local.split('.').all(is_atom) {
        return Syntax::Invalid("invalid_local_part");
    }

    // domain_to_ascii lower-cases the domain and converts international names to punycode.
    let Ok(domain) = idna::domain_to_ascii(raw_domain.trim_end_matches('.')) else {
        return Syntax::Invalid("invalid_domain");
    };
    let labels: Vec<&str> = domain.split('.').collect();
    if labels.len() < 2
        || labels.last().unwrap().bytes().all(|b| b.is_ascii_digit())
        || !labels.iter().all(|l| is_label(l))
    {
        return Syntax::Invalid("invalid_domain");
    }
    Syntax::Ok {
        normalized: format!("{}@{}", local.to_lowercase(), domain),
        local: local.to_string(),
        domain,
    }
}

Notes on the code:

  • idna::domain_to_ascii() converts international domains to punycode (münchen.de becomes xn--mnchen-3ya.de), which is the form DNS needs, and lower-cases them.
  • rsplit_once('@') splits at the last @, so a stray @ in the local part fails the atom check rather than becoming part of the domain.
  • split('.') keeps empty parts, so .jane, jane. and ja..ne all fail with no extra rules.
  • len() on a &str counts bytes, which is exactly what RFC 5321's 64-byte local part limit means.

Only lower-case the local part when comparing addresses, to stop duplicate sign-ups. Store what the user typed, because a few mail servers still treat Jane and jane as different mailboxes.

2. Check the domain's MX records

A well-formed address is no use if its domain doesn't exist or doesn't accept mail. The domain's MX (mail exchanger) records name the servers that receive its mail. hickory-resolver's errors say whether the domain doesn't exist (is_nx_domain()) or just has no records of that type (is_no_records_found()), so each case gets the right status:

src/dns.rs
use hickory_resolver::TokioResolver;
use hickory_resolver::proto::rr::RData;

#[derive(Clone, Debug, PartialEq)]
pub enum DomainCheck {
    Ok(Vec<String>),
    Risky(&'static str),
    Invalid(&'static str),
    Unknown,
}

pub async fn check_domain(resolver: &TokioResolver, domain: &str) -> DomainCheck {
    // The trailing dot stops the resolver from trying "domain.your-search-domain" too.
    let fqdn = format!("{domain}.");
    match resolver.mx_lookup(fqdn.as_str()).await {
        Ok(lookup) => {
            let mut mx: Vec<_> = lookup
                .answers()
                .iter()
                .filter_map(|record| match &record.data {
                    RData::MX(mx) => Some((mx.preference, mx.exchange.clone())),
                    _ => None,
                })
                .collect();
            mx.sort_by_key(|(preference, _)| *preference);
            // RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
            if mx.len() == 1 && mx[0].1.is_root() {
                return DomainCheck::Invalid("domain_rejects_mail");
            }
            if !mx.is_empty() {
                return DomainCheck::Ok(
                    mx.into_iter()
                        .map(|(_, host)| host.to_string().trim_end_matches('.').to_string())
                        .collect(),
                );
            }
        }
        Err(e) if e.is_nx_domain() => return DomainCheck::Invalid("domain_not_found"),
        // No records of this type: handled below. Anything else is temporary, so don't blame the user.
        Err(e) if !e.is_no_records_found() => return DomainCheck::Unknown,
        Err(_) => {}
    }

    // No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
    let has_address = resolver.ipv4_lookup(fqdn.as_str()).await.is_ok()
        || resolver.ipv6_lookup(fqdn.as_str()).await.is_ok();
    if has_address {
        DomainCheck::Risky("no_mx_records")
    } else {
        DomainCheck::Invalid("no_mail_server")
    }
}
ResultMeaningStatus
MX records returnedThe domain accepts mailok
One MX record with an empty name"Null MX" (RFC 7505): the domain accepts no mailinvalid
Error where is_nx_domain() is trueThe domain doesn't existinvalid
Error where is_no_records_found() is trueThe domain exists but has no MX records, so check A/AAAArisky or invalid
Any other errorSERVFAIL or a timeout: DNS trouble, not the user's faultunknown

Keep the resolver's timeout short, so a slow DNS server can't hold up a sign-up (step 6 sets three seconds), and never treat a timeout as "invalid", or you'll turn away real users whenever DNS has a bad moment.

3. Cache DNS lookups

Most of your users share a handful of domains like gmail.com and outlook.com. A Rust server is one long-running process, so a map shared by all requests saves most lookups:

src/cache.rs
use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::dns::DomainCheck;

const TTL: Duration = Duration::from_secs(3600);

/// Remembers DNS results for an hour. A Mutex makes it safe to share between requests.
#[derive(Default)]
pub struct DomainCache(Mutex<HashMap<String, (DomainCheck, Instant)>>);

impl DomainCache {
    pub fn get(&self, domain: &str) -> Option<DomainCheck> {
        let map = self.0.lock().unwrap();
        map.get(domain)
            .filter(|(_, expires)| *expires > Instant::now())
            .map(|(result, _)| result.clone())
    }

    pub fn put(&self, domain: &str, result: &DomainCheck) {
        // Don't remember temporary failures.
        if *result != DomainCheck::Unknown {
            self.0
                .lock()
                .unwrap()
                .insert(domain.to_string(), (result.clone(), Instant::now() + TTL));
        }
    }
}

The lock is only held while reading or writing the map, never across the DNS .await, so a slow lookup doesn't block other requests. hickory-resolver also has its own response cache; ours stores the final verdict and lets us skip failed lookups. Don't cache temporary failures.

4. Detect disposable domains

Temporary inboxes from services like Mailinator pass every check so far: the syntax is fine and the domains have working mail servers. The only way to catch them is a list. Download the community-maintained disposable-email-domains list next to your binary:

curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf
src/disposable.rs
use std::collections::HashSet;

/// The disposable-domain list. A HashSet makes each lookup instant.
pub struct Blocklist(HashSet<String>);

impl Blocklist {
    /// Parses the list: one domain per line.
    pub fn parse(text: &str) -> Self {
        Self(
            text.lines()
                .map(str::trim)
                .filter(|l| !l.is_empty())
                .map(String::from)
                .collect(),
        )
    }

    /// Checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com".
    pub fn contains(&self, domain: &str) -> bool {
        let labels: Vec<&str> = domain.split('.').collect();
        (0..labels.len().saturating_sub(1)).any(|i| self.0.contains(&labels[i..].join(".")))
    }
}

Checking parent domains matters because many disposable services hand out addresses on random subdomains. New disposable domains appear every week, so download the list again from a daily job and restart. To ship a single binary, pass include_str!("../disposable_email_blocklist.conf") instead of reading the file at start-up.

The list also contains some typo domains, such as gmial.com and hotmial.com. Someone registered them to collect mail meant for Gmail and Hotmail users, which is why step 6 still returns a did_you_mean suggestion for a disposable address. Read more about how disposable email detection works.

5. Flag role accounts and suggest typo fixes

Flag role accounts and typos too. Role accounts like info@ and support@ reach a shared inbox rather than a person, and typos like gamil.com are one of the commonest reasons a sign-up email never arrives:

src/extras.rs
const ROLE_ACCOUNTS: &[&str] = &[
    "admin",
    "billing",
    "contact",
    "help",
    "hello",
    "info",
    "marketing",
    "no-reply",
    "noreply",
    "office",
    "postmaster",
    "sales",
    "support",
    "team",
    "webmaster",
];

pub fn is_role_account(local: &str) -> bool {
    // Ignore "+tag" sub-addressing: "support+billing" is still "support".
    let lower = local.to_lowercase();
    ROLE_ACCOUNTS.contains(&lower.split('+').next().unwrap_or(""))
}

// Real providers people mistype. Include close neighbours (mail.com, ymail.com, gmx.com…)
// too, or they'd be "corrected" to the provider one letter away.
const POPULAR_DOMAINS: &[&str] = &[
    "gmail.com",
    "googlemail.com",
    "yahoo.com",
    "ymail.com",
    "yahoo.co.uk",
    "hotmail.com",
    "hotmail.co.uk",
    "outlook.com",
    "live.com",
    "msn.com",
    "icloud.com",
    "me.com",
    "mac.com",
    "aol.com",
    "mail.com",
    "gmx.com",
    "gmx.de",
    "proton.me",
    "protonmail.com",
];

/// Levenshtein distance: the number of single-character edits between two strings.
fn edit_distance(a: &str, b: &str) -> usize {
    let (a, b) = (a.as_bytes(), b.as_bytes()); // domains are ASCII after punycode
    let mut prev: Vec<usize> = (0..=b.len()).collect();
    for i in 1..=a.len() {
        let mut row = vec![i; b.len() + 1];
        for j in 1..=b.len() {
            let cost = usize::from(a[i - 1] != b[j - 1]);
            row[j] = (prev[j] + 1).min(row[j - 1] + 1).min(prev[j - 1] + cost);
        }
        prev = row;
    }
    prev[b.len()]
}

/// "gmial.com" → Some("gmail.com"); None when the domain is fine or nothing is close.
pub fn suggest_domain(domain: &str) -> Option<&'static str> {
    if POPULAR_DOMAINS.contains(&domain) {
        return None;
    }
    let (best, distance) = POPULAR_DOMAINS
        .iter()
        .map(|c| (*c, edit_distance(domain, c)))
        .min_by_key(|(_, d)| *d)?;
    // Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
    (distance <= if domain.len() <= 6 { 1 } else { 2 }).then_some(best)
}

The Levenshtein distance counts two swapped letters (gmial → gmail) as two edits, which the two-edit limit for longer domains still allows. Short domains only get one edit's leeway, because a two-letter difference on me.com is a different domain. If you'd rather not write it yourself, the strsim crate has levenshtein().

Choose the list of domains carefully. Real providers that sit one letter apart, like mail.com and gmail.com, must both be in it, or users of one get "corrected" to the other. Even then, some genuine domains will look like typos, so show the result as a suggestion and let the user decide.

6. Put it together

Now tie it together in one struct that owns the resolver, the cache and the blocklist, and runs the checks from cheapest to most expensive:

src/lib.rs
pub mod api_client;
mod cache;
mod disposable;
mod dns;
mod extras;
pub mod server;
mod syntax;

use std::time::Duration;

use hickory_resolver::TokioResolver;
use hickory_resolver::config::ResolverOpts;
use serde::Serialize;

pub use dns::DomainCheck;
pub use syntax::{Syntax, check_syntax};

/// status is "valid", "invalid", "risky" or "unknown".
#[derive(Debug, Serialize)]
pub struct Verdict {
    pub status: &'static str,
    pub reason: &'static str,
    pub email: Option<String>,
    pub did_you_mean: Option<String>,
}

/// Holds the resolver, cache and blocklist. Create one and share it (e.g. in an Arc).
pub struct EmailValidator {
    resolver: TokioResolver,
    cache: cache::DomainCache,
    blocklist: disposable::Blocklist,
}

impl EmailValidator {
    /// Uses the system's DNS servers (/etc/resolv.conf) and a disposable list, one domain per line.
    pub fn new(blocklist: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let mut opts = ResolverOpts::default();
        // A short timeout, so a slow DNS server can't stall a sign-up.
        opts.timeout = Duration::from_secs(3);
        opts.attempts = 2;
        let resolver = TokioResolver::builder_tokio()?.with_options(opts).build()?;
        Ok(Self::with_resolver(resolver, blocklist))
    }

    pub fn with_resolver(resolver: TokioResolver, blocklist: &str) -> Self {
        Self {
            resolver,
            cache: Default::default(),
            blocklist: disposable::Blocklist::parse(blocklist),
        }
    }

    async fn check_domain_cached(&self, domain: &str) -> DomainCheck {
        if let Some(hit) = self.cache.get(domain) {
            return hit;
        }
        let result = dns::check_domain(&self.resolver, domain).await;
        self.cache.put(domain, &result);
        result
    }

    pub async fn validate(&self, input: &str) -> Verdict {
        let (local, domain, normalized) = match check_syntax(input) {
            Syntax::Ok {
                local,
                domain,
                normalized,
            } => (local, domain, normalized),
            Syntax::Invalid(reason) => {
                return Verdict {
                    status: "invalid",
                    reason,
                    email: None,
                    did_you_mean: None,
                };
            }
        };
        let suggestion = extras::suggest_domain(&domain);
        let verdict = |status, reason| Verdict {
            status,
            reason,
            email: Some(normalized.clone()),
            did_you_mean: suggestion.map(|s| format!("{local}@{s}")),
        };

        let dns = self.check_domain_cached(&domain).await;
        match dns {
            DomainCheck::Invalid(reason) => return verdict("invalid", reason),
            DomainCheck::Unknown => return verdict("unknown", "dns_error"),
            _ => {}
        }

        // The domain can receive mail. Now look for risk signals, most serious first.
        if self.blocklist.contains(&domain) {
            verdict("risky", "disposable")
        } else if suggestion.is_some() {
            verdict("risky", "possible_typo")
        } else if let DomainCheck::Risky(reason) = dns {
            verdict("risky", reason)
        } else if extras::is_role_account(&local) {
            verdict("risky", "role_based")
        } else {
            verdict("valid", "mail_server_found")
        }
    }
}

validate() returns these results for a range of inputs:

Inputstatusreasondid_you_mean
jane@gmail.comvalidmail_server_foundNone
joe@gamil.comriskypossible_typojoe@gmail.com
test@mailinator.comriskydisposableNone
support@acme.ioriskyrole_basedNone
x@no-such-domain.exampleinvaliddomain_not_foundNone
not-an-emailinvalidmissing_at_or_partNone

7. Use it in an axum handler

A typical sign-up policy is to reject invalid and disposable addresses, accept everything else, and pass the typo suggestion back so the front end can ask "Did you mean …?". Share one validator between requests as axum state:

src/server.rs
use std::sync::Arc;

use axum::extract::State;
use axum::http::StatusCode;
use axum::routing::post;
use axum::{Json, Router};
use serde::Deserialize;
use serde_json::{Value, json};

use crate::EmailValidator;

#[derive(Deserialize)]
pub struct SignupRequest {
    email: String,
}

async fn signup(
    State(validator): State<Arc<EmailValidator>>,
    Json(body): Json<SignupRequest>,
) -> (StatusCode, Json<Value>) {
    let result = validator.validate(&body.email).await;

    if result.status == "invalid" || result.reason == "disposable" {
        let error = if result.reason == "disposable" {
            "Please use a permanent email address."
        } else {
            "That email address can't receive mail."
        };
        return (
            StatusCode::UNPROCESSABLE_ENTITY,
            Json(json!({ "error": error, "did_you_mean": result.did_you_mean })),
        );
    }

    // "unknown" means DNS had a hiccup. Accept the address and check it again later.
    // create_user(&result.email).await;
    (
        StatusCode::CREATED,
        Json(json!({ "ok": true, "email": result.email, "did_you_mean": result.did_you_mean })),
    )
}

pub fn router(validator: Arc<EmailValidator>) -> Router {
    Router::new()
        .route("/signup", post(signup))
        .with_state(validator)
}

And start the server:

src/bin/server.rs
use std::sync::Arc;

use emailcheck::{EmailValidator, server};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let blocklist = std::fs::read_to_string("disposable_email_blocklist.conf")?;
    let validator = Arc::new(EmailValidator::new(&blocklist)?);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
    axum::serve(listener, server::router(validator)).await?;
    Ok(())
}

Adjust the policy to your product: a B2B form might also reject free providers, while a newsletter might accept role accounts.

8. Test it

The syntax check has no side effects, so plain integration tests cover it:

tests/syntax.rs
use emailcheck::{Syntax, check_syntax};

#[test]
fn accepts_normal_addresses() {
    for email in [
        "jane@example.com",
        "jane.doe+news@example.co.uk",
        "user@münchen.de",
    ] {
        assert!(matches!(check_syntax(email), Syntax::Ok { .. }), "{email}");
    }
}

#[test]
fn rejects_malformed_addresses() {
    for email in [
        "",
        "jane",
        "@example.com",
        "jane@",
        "a..b@example.com",
        "jane@example",
        "jane@-example.com",
    ] {
        assert!(matches!(check_syntax(email), Syntax::Invalid(_)), "{email}");
    }
}

For the DNS checks, build a resolver with ResolverConfig::from_parts() and a NameServerConfig for 127.0.0.1 on port 5353, pass it to EmailValidator::with_resolver(), and run a local test DNS server. Then cargo test doesn't depend on the internet. That's how we tested every result on this page, including the axum handler with tower::ServiceExt::oneshot.

What about checking that the mailbox exists?

You could go further with a TCP connection: connect to the domain's mail server on port 25 and ask whether a specific mailbox exists with RCPT TO. We don't recommend doing that inside a request. Many hosting providers block outbound port 25, large providers often accept every recipient at that stage, and catch-all domains and greylisting make the answer inconclusive.

For most sign-up forms, the checks above plus a confirmation email are the best balance of accuracy and speed.

Or use an email validation API

Everything above works, but you have to maintain it: the disposable list goes stale, the typo list needs tuning, and DNS edge cases keep turning up. The validateemail.io API runs all of these checks in one request. With reqwest (cargo add reqwest --features json):

src/api_client.rs
use std::time::Duration;

use serde::Deserialize;
use serde_json::json;

const API: &str = "https://validateemail.io/v1";

#[derive(Debug, Deserialize)]
pub struct ApiResult {
    pub email: Option<String>,
    pub status: String,
    pub reason: String,
    pub did_you_mean: Option<String>,
}

#[derive(Deserialize)]
struct BatchResponse {
    results: Vec<ApiResult>,
}

pub struct ValidateEmailApi {
    http: reqwest::Client,
    key: String,
}

impl ValidateEmailApi {
    pub fn new(key: String) -> Self {
        Self {
            http: reqwest::Client::new(),
            key,
        }
    }

    async fn post<T: serde::de::DeserializeOwned>(
        &self,
        path: &str,
        body: serde_json::Value,
        timeout: Duration,
    ) -> reqwest::Result<T> {
        self.http
            .post(format!("{API}{path}"))
            .bearer_auth(&self.key)
            .json(&body)
            .timeout(timeout)
            .send()
            .await?
            .error_for_status()?
            .json()
            .await
    }

    pub async fn validate(&self, email: &str) -> ApiResult {
        match self
            .post(
                "/validate",
                json!({ "email": email }),
                Duration::from_secs(5),
            )
            .await
        {
            Ok(result) => result,
            Err(e) => {
                // Never block a sign-up because the validator is slow or unreachable.
                eprintln!("Email validation unavailable: {e}");
                ApiResult {
                    email: Some(email.into()),
                    status: "unknown".into(),
                    reason: "validator_unavailable".into(),
                    did_you_mean: None,
                }
            }
        }
    }

    /// Validates any number of addresses, 100 per request.
    pub async fn validate_list(&self, emails: &[String]) -> reqwest::Result<Vec<ApiResult>> {
        let mut results = Vec::with_capacity(emails.len());
        for chunk in emails.chunks(100) {
            let page: BatchResponse = self
                .post(
                    "/validate/batch",
                    json!({ "emails": chunk }),
                    Duration::from_secs(30),
                )
                .await?;
            results.extend(page.results);
        }
        Ok(results)
    }
}

If the API is slow or unreachable, validate() returns unknown instead of an error, so a network problem never blocks a sign-up. The response has the same status, reason and did_you_mean fields used in this guide, plus a score and the result of every individual check.

Using an AI coding assistant? Paste this prompt and it will wire up the API for you:

Prompt for Cursor, Claude Code, Lovable or Copilot
Add email validation to the sign-up handler of this Rust (axum) app using the validateemail.io API (reference: https://validateemail.io/llms.txt).

- Call POST https://validateemail.io/v1/validate from server-side code only, with the header "Authorization: Bearer <key>" read from the VALIDATEEMAIL_KEY environment variable, and the JSON body {"email": "<address>"}. Never call it from the browser.
- Reject the address with a clear message when "status" is "invalid" or "checks.disposable" is true.
- When "did_you_mean" is set, show "Did you mean <did_you_mean>?" and let the user accept the fix.
- Use a 5-second timeout. If the API fails, times out or returns "status": "unknown", accept the address so sign-ups never break.
- Add a test that mocks the API for a valid, an invalid and a disposable address.

Frequently asked questions

Which crate should I use to validate emails in Rust?

Crates like email_address or validator check the format only. To know whether the domain can receive mail, add an MX lookup with hickory-resolver, plus a disposable-domain list and typo suggestions, as this guide does.

How do I look up MX records in Rust?

Use hickory-resolver: TokioResolver::builder_tokio()?.build()?, then resolver.mx_lookup("example.com.").await. On error, is_nx_domain() means the domain doesn't exist and is_no_records_found() means it exists but has no MX records.

Why does the domain end with a dot in the lookup?

A trailing dot makes the name fully qualified. Without it, the resolver may also try the name with your machine's search domains appended, such as example.com.corp.internal, which wastes queries.

Can Rust check that a mailbox exists without sending an email?

You can try by connecting to the domain's mail server on port 25 and sending RCPT TO. In practice port 25 is often blocked, large providers accept every recipient at that stage, and catch-all domains accept anything, so the answer is often unreliable. A confirmation email is still the only definitive test.