Code samples · Ruby

Ruby code samples

Copy-paste Ruby examples that validate one address, send the API key in the Authorization header, retry 429 and 503 answers after Retry-After when the wait is at most 10 seconds (never key_daily_cap, which lasts until the next UTC day), and report other errors with their code and request id. Each uses the free test address accepted@sandbox.email-validation.org; replace it with a real address when you are ready. The same samples in other languages: all code samples.

Set your key first: export EV_API_KEY="ev_live_…".

The samples call https://api.email-validation.org. For EU data residency, replace it with https://api-eu.email-validation.org, or pass the SDK's EU base URL constant; there /v1/validate takes POST only (EU data residency).

With the official SDK

The official Ruby SDK does the retries, timeouts and error mapping for you: one call validates an address and every failure arrives as a typed error. There are official SDKs for JavaScript/TypeScript, Python, Go, PHP, Ruby, C#, Rust and Swift; those for Java, Kotlin, Dart, Elixir, C and Perl are built and tested and coming soon to their package registries. The plain HTTP samples further down call the API directly.

Ruby

require "email_validation_sdk"

client = EmailValidation::Client.new(api_key: ENV.fetch("EV_API_KEY"))

begin
  result = client.validate("accepted@sandbox.email-validation.org")
  puts "#{result.status} #{result.reason} #{result.action}" # valid accepted send
rescue EmailValidation::InsufficientCreditsError
  puts "buy credits; nothing was charged"
rescue EmailValidation::Error => e
  puts "#{e.code} #{e.request_id}"
end

Validate an address

Ruby

require "json"
require "net/http"
require "uri"

API = URI("https://api.email-validation.org/v1/validate")
MAX_WAIT_S = 10 # never wait out a long Retry-After (key_daily_cap lasts until the next UTC day)

def validate(email, attempts: 3)
  attempt = 0
  loop do
    attempt += 1
    req = Net::HTTP::Post.new(API)
    req["Authorization"] = "Bearer #{ENV.fetch("EV_API_KEY")}"
    req["Content-Type"] = "application/json"
    req.body = JSON.generate(email: email)
    res = Net::HTTP.start(API.host, API.port, use_ssl: true, read_timeout: 20) { |http| http.request(req) }
    return JSON.parse(res.body) if res.is_a?(Net::HTTPSuccess)

    error = JSON.parse(res.body).fetch("error")
    wait = [Integer(res["Retry-After"] || "1"), 1].max
    if %w[429 503].include?(res.code) && error["code"] != "key_daily_cap" && wait <= MAX_WAIT_S && attempt < attempts
      sleep(wait)
      next
    end
    raise "#{error["code"]}: #{error["message"]} (#{error["request_id"]})"
  end
end

result = validate("accepted@sandbox.email-validation.org")
puts [result["status"], result["reason"], result["action"]].join(" ")

Verify a webhook

Ruby

require "json"
require "openssl"

def verify_webhook(raw_body, headers, secret, tolerance: 300)
  id = headers["webhook-id"]
  timestamp = headers["webhook-timestamp"]
  signatures = headers["webhook-signature"]
  raise ArgumentError, "missing webhook headers" unless id && timestamp && signatures
  unless timestamp.match?(/\A\d+\z/) && (Time.now.to_i - timestamp.to_i).abs <= tolerance
    raise ArgumentError, "timestamp outside tolerance"
  end

  key = secret.delete_prefix("whsec_").unpack1("m0")
  expected = [OpenSSL::HMAC.digest("SHA256", key, "#{id}.#{timestamp}.#{raw_body}")].pack("m0")
  valid = signatures.split(" ").any? do |entry|
    version, sig = entry.split(",", 2)
    version == "v1" && sig && OpenSSL.secure_compare(sig, expected)
  end
  raise ArgumentError, "no valid signature" unless valid

  JSON.parse(raw_body)
end

# Rails: verify_webhook(request.raw_post, request.headers, ENV.fetch("EV_WEBHOOK_SECRET"))

Other calls

  • Read the credit balance: samples in curl, JavaScript and Python (all code samples).
  • Create a bulk job: samples in curl, JavaScript and Python (all code samples).

Notes

  • Use POST with a JSON body; it keeps addresses out of URLs and logs.
  • Set the HTTP timeout to about 20 seconds: a check may take up to 15 seconds (10 by default).
  • A 200 answer with the status unknown is a normal, free result, not an error.
  • Every endpoint, field and error: the API reference.

Updated · Maintained by: Email Validation LLC

Need help? Contact support, or ask the help chat. Something wrong or missing on this page? Tell us