How to validate email addresses in Ruby and Rails

Build an email validator in Ruby step by step: syntax checks, MX lookups, disposable-domain detection, typo suggestions, a Sinatra sign-up endpoint and a Rails validator.

What we'll build

A regular expression or URI::MailTo::EMAIL_REGEXP can tell you an address looks right. Neither can tell you whether the domain exists, whether it accepts mail, or whether it's a throwaway inbox. In this guide we'll build an EmailCheck.validate method that 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 Ruby 3.3 or later and two gems: dnsruby for DNS lookups and simpleidn for international domain names. Add them to your Gemfile:

bundle add dnsruby simpleidn

Every snippet was tested with Ruby 3.3, dnsruby 2.0, Sinatra 4.2 and Rails (ActiveModel) 8.1. 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 one huge regular expression, split the address at the last @ and check each part separately. The rules stay readable, and you can say exactly what's wrong:

syntax.rb
require "simpleidn"

module EmailCheck
  # RFC 5322 "atext": the characters allowed in each dot-separated part of the local part.
  ATOM = %r{\A[a-z0-9!#$%&'*+/=?^_`{|}~-]+\z}i
  # A DNS label: letters, digits and hyphens, not starting or ending with a hyphen.
  LABEL = /\A[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\z/

  # Lower-cases a domain and converts international names to punycode, or returns nil.
  def self.to_ascii_domain(domain)
    SimpleIDN.to_ascii(domain.strip.chomp(".")).downcase
  rescue StandardError
    nil
  end

  def self.check_syntax(input)
    email = input.to_s.strip
    return { ok: false, reason: "too_long" } if email.length > 254

    at = email.rindex("@")
    return { ok: false, reason: "missing_at_or_part" } if at.nil? || at.zero? || at == email.length - 1

    local = email[0...at]
    return { ok: false, reason: "local_part_too_long" } if local.bytesize > 64
    # split(".", -1) keeps empty parts, so leading, trailing and doubled dots fail.
    return { ok: false, reason: "invalid_local_part" } unless local.split(".", -1).all? { |atom| ATOM.match?(atom) }

    domain = to_ascii_domain(email[(at + 1)..])
    labels = domain.to_s.split(".", -1)
    if labels.length < 2 || labels.last.match?(/\A\d+\z/) || !labels.all? { |label| LABEL.match?(label) }
      return { ok: false, reason: "invalid_domain" }
    end

    { ok: true, local: local, domain: domain, normalized: "#{local.downcase}@#{domain}" }
  end
end

Notes on the code:

  • The patterns use \A and \z, not ^ and $. In Ruby, ^ and $ match at every line break, so "evil\njane" would pass a ^…$ check.
  • SimpleIDN.to_ascii converts international domains to punycode (münchen.de becomes xn--mnchen-3ya.de), which is the form DNS needs.
  • split(".", -1) keeps empty parts, so .jane, jane. and ja..ne all fail with no extra rules. Plain split(".") drops trailing empty parts and would let jane. through.
  • The local part limit is 64 bytes (RFC 5321), hence bytesize rather than length.

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.

Ruby's built-in Resolv returns an empty list both for a domain that doesn't exist and for one with no MX records, and you need to treat those cases differently. dnsruby raises Dnsruby::NXDomain for a missing domain, so each case gets the right status:

dns_check.rb
require "dnsruby"

module EmailCheck
  # Uses the servers in /etc/resolv.conf, with a short timeout so a slow DNS server can't stall a sign-up.
  def self.resolver
    @resolver ||= Dnsruby::Resolver.new(query_timeout: 3)
  end

  def self.has_address?(domain)
    %w[A AAAA].any? do |type|
      resolver.query(domain, type).answer.any? { |rr| rr.type.to_s == type }
    rescue Dnsruby::ResolvError, Dnsruby::ResolvTimeout
      false
    end
  end

  def self.check_domain(domain)
    begin
      answer = resolver.query(domain, "MX").answer
    rescue Dnsruby::NXDomain
      return { status: "invalid", reason: "domain_not_found" }
    rescue Dnsruby::ResolvError, Dnsruby::ResolvTimeout
      # SERVFAIL, timeouts and other DNS trouble are temporary. Don't blame the user.
      return { status: "unknown", reason: "dns_error" }
    end

    mx = answer.select { |rr| rr.type.to_s == "MX" }.sort_by(&:preference)
    # RFC 7505 "null MX": a single record pointing at "." means "this domain accepts no mail".
    return { status: "invalid", reason: "domain_rejects_mail" } if mx.length == 1 && mx.first.exchange.to_s.empty?
    return { status: "ok", mx: mx.map { |rr| rr.exchange.to_s } } if mx.any?

    # No MX records: mail servers fall back to the domain's own A/AAAA record ("implicit MX").
    if has_address?(domain)
      { status: "risky", reason: "no_mx_records" }
    else
      { status: "invalid", reason: "no_mail_server" }
    end
  end
end
ResultMeaningStatus
MX records returnedThe domain accepts mailok
One MX record with an empty name"Null MX" (RFC 7505): the domain accepts no mailinvalid
Dnsruby::NXDomain raisedThe domain doesn't existinvalid
Empty answerThe domain exists but has no MX records, so check A/AAAArisky or invalid
Another ResolvError or ResolvTimeoutSERVFAIL 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, 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 Puma or Sidekiq process serves many requests, so an in-memory hash saves most lookups:

dns_cache.rb
require_relative "dns_check"

module EmailCheck
  CACHE = {}
  CACHE_LOCK = Mutex.new

  def self.check_domain_cached(domain)
    hit = CACHE_LOCK.synchronize { CACHE[domain] }
    return hit[:result] if hit && hit[:expires] > Time.now

    result = check_domain(domain)
    # Don't remember temporary failures.
    CACHE_LOCK.synchronize { CACHE[domain] = { result: result, expires: Time.now + 3600 } } unless result[:status] == "unknown"
    result
  end
end

Puma runs requests on several threads, so the hash is guarded by a mutex. Each worker process keeps its own cache; to share one across processes, use Rails.cache.fetch(domain, expires_in: 1.hour) with the same rule. Don't cache failed lookups.

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 code:

curl -fsSo disposable_email_blocklist.conf https://raw.githubusercontent.com/disposable-email-domains/disposable-email-domains/main/disposable_email_blocklist.conf
disposable.rb
require "set"

module EmailCheck
  # One domain per line. A Set makes each lookup instant.
  BLOCKLIST = File.readlines(File.join(__dir__, "disposable_email_blocklist.conf"), chomp: true).reject(&:empty?).to_set.freeze

  # Checks the domain and each parent, so "x.mailinator.com" matches "mailinator.com".
  def self.disposable?(domain)
    labels = domain.split(".")
    (0...labels.length - 1).any? { |i| BLOCKLIST.include?(labels[i..].join(".")) }
  end
end

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.

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:

extras.rb
module EmailCheck
  ROLE_ACCOUNTS = %w[
    admin billing contact help hello info marketing no-reply
    noreply office postmaster sales support team webmaster
  ].freeze

  def self.role_account?(local)
    # Ignore "+tag" sub-addressing: "support+billing" is still "support".
    ROLE_ACCOUNTS.include?(local.downcase.split("+").first)
  end

  # 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.
  POPULAR_DOMAINS = %w[
    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
  ].freeze

  # Levenshtein distance: the number of single-character edits between two strings.
  def self.edit_distance(a, b)
    prev = (0..b.length).to_a
    a.each_char.with_index(1) do |ca, i|
      row = [i]
      b.each_char.with_index(1) do |cb, j|
        row << [prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (ca == cb ? 0 : 1)].min
      end
      prev = row
    end
    prev.last
  end

  # "gmial.com" → "gmail.com"; nil when the domain is fine or nothing is close.
  def self.suggest_domain(domain)
    return nil if POPULAR_DOMAINS.include?(domain)

    best = POPULAR_DOMAINS.min_by { |candidate| edit_distance(domain, candidate) }
    # Short domains only get one edit's leeway: two letters off "me.com" is a different domain.
    edit_distance(domain, best) <= (domain.length <= 6 ? 1 : 2) ? best : nil
  end
end

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.

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 run the checks from cheapest to most expensive and return a single verdict:

validate_email.rb
require_relative "syntax"
require_relative "dns_cache"
require_relative "disposable"
require_relative "extras"

module EmailCheck
  # Returns { status:, reason:, email:, did_you_mean: } where status is
  # "valid", "invalid", "risky" or "unknown".
  def self.validate(input)
    syntax = check_syntax(input)
    return { status: "invalid", reason: syntax[:reason], email: nil, did_you_mean: nil } unless syntax[:ok]

    local, domain = syntax.values_at(:local, :domain)
    suggestion = suggest_domain(domain)
    base = { email: syntax[:normalized], did_you_mean: suggestion && "#{local}@#{suggestion}" }

    dns = check_domain_cached(domain)
    return base.merge(status: dns[:status], reason: dns[:reason]) if %w[invalid unknown].include?(dns[:status])

    # The domain can receive mail. Now look for risk signals, most serious first.
    reason =
      if disposable?(domain) then "disposable"
      elsif suggestion then "possible_typo"
      elsif dns[:status] == "risky" then dns[:reason]
      elsif role_account?(local) then "role_based"
      end
    base.merge(status: reason ? "risky" : "valid", reason: reason || "mail_server_found")
  end
end

It returns these results for a range of inputs:

Inputstatusreasondid_you_mean
jane@gmail.comvalidmail_server_foundnil
joe@gamil.comriskypossible_typojoe@gmail.com
test@mailinator.comriskydisposablenil
support@acme.ioriskyrole_basednil
x@no-such-domain.exampleinvaliddomain_not_foundnil
not-an-emailinvalidmissing_at_or_partnil

7. Use it in Sinatra or Rails

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 …?". As a Sinatra endpoint that takes JSON:

app.rb
require "sinatra"
require "json"
require_relative "validate_email"

post "/signup" do
  content_type :json
  body = JSON.parse(request.body.read) rescue {}
  result = EmailCheck.validate(body.is_a?(Hash) ? body["email"].to_s : "")

  if result[:status] == "invalid" || result[:reason] == "disposable"
    halt 422, {
      error: result[:reason] == "disposable" ? "Please use a permanent email address." : "That email address can't receive mail.",
      did_you_mean: result[:did_you_mean],
    }.to_json
  end

  # "unknown" means DNS had a hiccup. Accept the address and check it again later.
  # User.create!(email: result[:email])
  status 201
  { ok: true, email: result[:email], did_you_mean: result[:did_you_mean] }.to_json
end

In Rails, the usual format: { with: URI::MailTo::EMAIL_REGEXP } covers step 1 only. A custom validator adds the rest. Put the files from steps 1 to 6 in lib/email_check/ and require them from an initializer, then add:

app/validators/deliverable_email_validator.rb
# Usage in a model:  validates :email, presence: true, deliverable_email: true
class DeliverableEmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    result = EmailCheck.validate(value.to_s)

    if result[:status] == "invalid"
      record.errors.add(attribute, options[:message] || "can't receive mail")
    elsif result[:reason] == "disposable"
      record.errors.add(attribute, "must be a permanent email address")
    end
  end
end

Rails loads anything in app/validators automatically, so validates :email, deliverable_email: true works in any model. 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 it's easy to test with Minitest:

test/syntax_test.rb
require "minitest/autorun"
require_relative "../syntax"

class SyntaxTest < Minitest::Test
  def test_accepts_normal_addresses
    ["jane@example.com", "jane.doe+news@example.co.uk", "user@münchen.de"].each do |email|
      assert EmailCheck.check_syntax(email)[:ok], email
    end
  end

  def test_rejects_malformed_addresses
    ["", "jane", "@example.com", "jane@", "a..b@example.com", "jane@example", "jane@-example.com"].each do |email|
      refute EmailCheck.check_syntax(email)[:ok], email
    end
  end
end

For the DNS checks, give dnsruby a local test DNS server with Dnsruby::Resolver.new(nameserver: "127.0.0.1", port: 5353). Then your test suite doesn't depend on the internet. That's how we tested every result on this page, including the Sinatra endpoint and the Rails validator.

What about checking that the mailbox exists?

You could go further with Net::SMTP: 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:

api_client.rb
require "json"
require "net/http"

module ValidateEmailApi
  BASE = URI("https://validateemail.io/v1")

  def self.request(path, body, timeout: 5)
    uri = URI("#{BASE}#{path}")
    Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: timeout, read_timeout: timeout) do |http|
      req = Net::HTTP::Post.new(uri, "Authorization" => "Bearer #{ENV.fetch("VALIDATEEMAIL_KEY")}", "Content-Type" => "application/json")
      req.body = body.to_json
      res = http.request(req)
      raise "HTTP #{res.code}" unless res.is_a?(Net::HTTPSuccess)

      JSON.parse(res.body)
    end
  end

  def self.validate(email)
    request("/validate", { email: email })
  rescue StandardError => e
    # Never block a sign-up because the validator is slow or unreachable.
    warn "Email validation unavailable: #{e.message}"
    { "status" => "unknown", "reason" => "validator_unavailable" }
  end

  # Validates any number of addresses, 100 per request.
  def self.validate_list(emails)
    emails.each_slice(100).flat_map { |chunk| request("/validate/batch", { emails: chunk }, timeout: 30)["results"] }
  end
end

If the API is slow or unreachable, ValidateEmailApi.validate returns unknown instead of raising, 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 flow of this Ruby on Rails (or Sinatra) 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

Is URI::MailTo::EMAIL_REGEXP enough to validate an email in Rails?

URI::MailTo::EMAIL_REGEXP is a reasonable format check. It can't tell you whether the domain exists or accepts mail, or whether the address is disposable or mistyped, so pair it with an MX lookup and the other checks in this guide, as the Rails validator in step 7 does.

How do I check if an email domain exists in Ruby?

Look up its MX records. The standard library's Resolv returns an empty list both for a domain that doesn't exist and for one with no MX records. dnsruby raises Dnsruby::NXDomain for a missing domain, so you can reject it and retry temporary failures instead.

Should I validate emails in a Rails model or a form object?

Either works with an ActiveModel::EachValidator. Running the DNS check in the model means every save of a user record triggers a lookup, so many apps only run it on create (on: :create) or in the sign-up form object.

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

You can try by connecting to the domain's mail server on port 25 with Net::SMTP 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.