Home / Developers / Ruby

Email verification API for Ruby

Verify one address or a whole list from Ruby in a few lines. The API is plain HTTPS and JSON: no SDK needed, one bearer key, and the examples below are complete and runnable.

Updated 2026-10-18

TL;DR

  • The Mail Exchange API is plain HTTPS and JSON at https://mailexchange.com/api/v1. No SDK needed.
  • POST /verify checks one address and usually answers in a few seconds. POST /lists checks up to 100,000 addresses and you poll for the result.
  • Each result has a state: deliverable, risky, undeliverable or unknown. The decision function below turns that into send, separate, skip, remove or retry.
  • Handle three statuses and you are done: 202 (still checking), 402 (out of credits) and 429 (slow down).

Get an API key

Keys are issued on request. Ask for one and we will set you up with free test credits. Every request sends the key as Authorization: Bearer your_key. Keep it in an environment variable, as the examples do, and out of source control. Credit prices are on the pricing page and credits never expire.

What you need

Ruby 3.0 or newer. Only the standard library is used (net/http and json), so there is nothing to install.

Net::HTTP is low level but dependable, and it keeps the example free of gems. If you already use Faraday or HTTParty, only the body of mx_call changes. In a Rails app, put the helper in a small service object and run the list example from a background job (Sidekiq, Solid Queue) rather than a web request, then fetch results when the webhook fires.

Verify one address in Ruby

Save this as verify.rb. It defines a small call helper that sends the key, retries on 429, and turns error responses into an exception or error value with the message from the API. Then verify_one posts the address and handles the one tricky case: a slow mail server.

require "net/http"
require "json"

BASE = "https://mailexchange.com/api/v1"

class MXError < StandardError
  attr_reader :status

  def initialize(status, message)
    super("HTTP #{status}: #{message}")
    @status = status
  end
end

VERBS = { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.freeze

# One API call. Retries 429 with exponential backoff, raises MXError on other errors.
def mx_call(verb, path, body = nil, retries = 4)
  uri = URI(BASE + path)
  attempt = 0
  loop do
    req = VERBS.fetch(verb).new(uri)
    req["Authorization"] = "Bearer #{ENV.fetch('MAILEXCHANGE_API_KEY')}"
    req["Content-Type"] = "application/json"
    req.body = JSON.generate(body) if body
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 45) { |http| http.request(req) }
    status = res.code.to_i
    if status == 429 && attempt < retries
      sleep(2**attempt)
      attempt += 1
      next
    end
    data = (JSON.parse(res.body.to_s) rescue {})
    raise MXError.new(status, data["error"] || res.body) if status >= 400
    return [status, data]
  end
end

# Turn a result into an action: send, separate, skip, remove or retry.
def decide(result)
  case result["state"]
  when "deliverable" then "send"
  when "risky" then result["reason"] == "low_deliverability" ? "separate" : "skip" # catch-all vs role/disposable
  when "undeliverable" then "remove"
  else "retry" # unknown, or still pending
  end
end

def verify_one(email)
  status, data = mx_call(:post, "/verify", { email: email })
  return data unless status == 202

  # 202: the mail server is slow. The check is running and already paid for.
  # Do not post the address again, poll the list instead.
  36.times do
    sleep 5
    _, page = mx_call(:get, "/lists/#{data['list_id']}/results?limit=1")
    row = page["results"].first
    return row if row && row["state"] != "pending"
  end
  data # still pending after 3 minutes: look again later with the same list_id
end

begin
  res = verify_one(ARGV.fetch(0))
  puts "#{res['email']} #{res['state']} #{res['reason']} -> #{decide(res)}"
rescue MXError => e
  abort "Mail Exchange error: #{e.message}"
end

Run it:

MAILEXCHANGE_API_KEY=mx_live_xxx ruby verify.rb [email protected]

Typical output looks like [email protected] deliverable accepted_email -> send.

About the 202. Most checks finish within a few seconds. If a mail server is slow, /verify waits about 20 seconds and then returns 202 with {"state": "pending", "list_id": ...}. That check is already running and was already charged. Posting the same address again would start a second check and charge again, so read the result from /lists/{list_id}/results instead, as the code does. More in errors, credits and rate limits.

Read the result and decide what to do

A result is a flat JSON object: email, state, reason, score, and the flags accept_all, role, free, disposable, plus mx. The state is what you branch on. The reason tells you why, and matters for the risky group. The decide function in the code above maps it like this:

statereasondecide() returnsWhy
deliverableaccepted_emailsendThe mail server accepted the mailbox.
riskylow_deliverabilityseparateCatch-all domain. Cannot be confirmed either way. Send carefully or keep apart.
riskylow_quality, disposableskipRole address (info@, sales@) or a throwaway domain.
undeliverablerejected_email, invalid_domain, invalid_emailremoveWill bounce. Drop it.
unknownunavailable_smtp, no_connect, dns_errorretryThe server did not give a clear answer. The credit is refunded.

The function is deliberately small so you can change it. A cold email team might send separate addresses only from established inboxes, as described in catch-all emails and cold email. A signup form might accept risky addresses but block undeliverable ones. The full list of states is in email verification statuses, and how it works explains the six checks behind them.

Verify a list in Ruby

For more than a handful of addresses, submit one list instead of looping over /verify. You get a list ID straight away, poll GET /lists/{id} until its status is done (or failed), then page through /lists/{id}/results 1,000 rows at a time. Duplicates inside the list are removed and not charged. Save this as verify_list.rb with one address per line in emails.txt.

require "net/http"
require "json"

BASE = "https://mailexchange.com/api/v1"

class MXError < StandardError
  attr_reader :status

  def initialize(status, message)
    super("HTTP #{status}: #{message}")
    @status = status
  end
end

VERBS = { get: Net::HTTP::Get, post: Net::HTTP::Post, delete: Net::HTTP::Delete }.freeze

# One API call. Retries 429 with exponential backoff, raises MXError on other errors.
def mx_call(verb, path, body = nil, retries = 4)
  uri = URI(BASE + path)
  attempt = 0
  loop do
    req = VERBS.fetch(verb).new(uri)
    req["Authorization"] = "Bearer #{ENV.fetch('MAILEXCHANGE_API_KEY')}"
    req["Content-Type"] = "application/json"
    req.body = JSON.generate(body) if body
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, read_timeout: 45) { |http| http.request(req) }
    status = res.code.to_i
    if status == 429 && attempt < retries
      sleep(2**attempt)
      attempt += 1
      next
    end
    data = (JSON.parse(res.body.to_s) rescue {})
    raise MXError.new(status, data["error"] || res.body) if status >= 400
    return [status, data]
  end
end

# Turn a result into an action: send, separate, skip, remove or retry.
def decide(result)
  case result["state"]
  when "deliverable" then "send"
  when "risky" then result["reason"] == "low_deliverability" ? "separate" : "skip" # catch-all vs role/disposable
  when "undeliverable" then "remove"
  else "retry" # unknown, or still pending
  end
end

def verify_list(emails)
  _, created = mx_call(:post, "/lists", { emails: emails, name: "ruby-example" })
  id = created["id"]
  summary = nil
  loop do
    _, summary = mx_call(:get, "/lists/#{id}")
    puts "#{summary['checked']}/#{summary['total']} checked (#{summary['status']})"
    break if %w[done failed].include?(summary["status"])

    sleep 5
  end
  raise "list #{id} failed" if summary["status"] == "failed"

  results = []
  offset = 0
  loop do
    _, page = mx_call(:get, "/lists/#{id}/results?offset=#{offset}&limit=1000")
    results.concat(page["results"])
    break if page["results"].size < 1000

    offset += 1000
  end
  [summary, results]
end

begin
  emails = File.readlines(ARGV.fetch(0), chomp: true).map(&:strip).reject(&:empty?)
  summary, results = verify_list(emails)

  puts "counts: #{summary['counts']} duplicates removed: #{summary['duplicates_removed']}"
  buckets = results.group_by { |row| decide(row) }
  buckets.each { |action, rows| puts "#{action} #{rows.size}" }
  File.write("send.txt", (buckets["send"] || []).map { |row| row["email"] }.join("\n"))

  mx_call(:delete, "/lists/#{summary['id']}") # optional: remove the list and its results
rescue MXError => e
  abort "Mail Exchange error: #{e.message}"
end
MAILEXCHANGE_API_KEY=mx_live_xxx ruby verify_list.rb emails.txt

Instead of polling you can pass a callback_url and let us call you when the list is done, see webhooks and callbacks. The whole flow, including CSV download and deleting a list, is in verify a list with the API.

Errors, 402 and 429

Every error response is JSON with an error field, which the helper surfaces in the exception message. The ones to plan for:

  • 429 means you hit the per-key rate limit. The helper waits 1, 2, 4 and 8 seconds and tries again, which is safe because a rate-limited request does no work and costs nothing.
  • 402 means you do not have enough credits for the request. Retrying will not help. Stop, alert someone, and top up. GET /account returns your balance if you want to check first.
  • 401 means the key is missing or wrong. 400 means the request was malformed, for example no email, or a list over 100,000 addresses.

Details and a status code table are in errors, credits and rate limits.

Questions

Is there an official Ruby 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?

Keys are issued on request through the contact page, and they come with free test credits. 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.

Related