Skip to content

// frameworks and platforms

Via API

Ruby on Rails email verification with pingutil

A Rails User model typically validates email with URI::MailTo::EMAIL_REGEXP, which says nothing about whether the domain is a throwaway service or the mailbox exists. A custom EachValidator that calls pingutil adds errors to the record like any other validation, so a disposable or dead address never saves and the form shows why.

Where it connects: Active Model custom validator (ActiveModel::EachValidator)

What goes wrong without it

  • Devise lets any well-formed address register, and we keep finding batches of accounts on disposable domains.
  • Our Action Mailer welcome emails bounce for addresses that never existed.
  • Sales asks which signups are real companies and we have nothing on the user record to tell them.

What you can do with Ruby on Rails and pingutil

  • One validator, used on create

    Add validates :email, pingutil_email: { mailbox: true }, on: :create. It runs when the account is created, not on every profile update.

  • Typo hints in the errors

    When the mailbox check returns invalid with did_you_mean, the error message carries the suggestion, which your form already renders.

  • Keep checks cheap with Rails.cache

    Domain categories are cached for a day, so a burst from the same throwaway domain is rejected without another API call.

Set it up

  1. 1

    Create an API key in the pingutil dashboard and store it with bin/rails credentials:edit as pingutil_key.

  2. 2

    Add app/validators/pingutil_email_validator.rb; Rails autoloads it and maps pingutil_email: to the class.

  3. 3

    Use a shared cache store in production (Solid Cache, Redis or Memcached) so the backoff and categories work across processes.

  4. 4

    Declare the validation on the model with on: :create, keeping your format validation for syntax.

  5. 5

    Show record.errors[:email] in the form as you do for other validations.

app/validators/pingutil_email_validator.rb
# app/validators/pingutil_email_validator.rb  (Rails 7.1+ / 8)
require "net/http"
require "json"

class PingutilEmailValidator < ActiveModel::EachValidator
  API = URI("https://pingutil.com/v1/")

  def validate_each(record, attribute, value)
    email = value.to_s.strip.downcase
    domain = email.split("@").last
    return if domain.blank?

    # Cache the domain's category, never the per-address verdict.
    if Rails.cache.read("pingutil:category:#{domain}") == "disposable"
      return record.errors.add(attribute, :disposable, message: "must be a permanent address")
    end

    lookup = post("lookup", { input: email, skip_enrichment: true }, read_timeout: 2)
    if lookup
      Rails.cache.write("pingutil:category:#{lookup["domain"]}", lookup["category"], expires_in: 1.day)
      if lookup.dig("verdict", "is_spam")
        return record.errors.add(attribute, :spam, message: "can't be used, please use a different address")
      end
    end

    return unless options[:mailbox]

    check = post("verify", { email: email }, read_timeout: 5)
    if check && check["status"] == "invalid"
      hint = check["did_you_mean"] ? " (did you mean #{check["did_you_mean"]}?)" : ""
      record.errors.add(attribute, :mailbox, message: "doesn't exist#{hint}")
    end
  end

  private

  # Parsed JSON, or nil when pingutil is slow, down or rate limited (fail open).
  def post(path, body, read_timeout:)
    return nil if Rails.cache.exist?("pingutil:backoff")

    uri = API + path
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 1, read_timeout: read_timeout) do |http|
      req = Net::HTTP::Post.new(uri,
        "Authorization" => "Bearer #{Rails.application.credentials.pingutil_key}",
        "Content-Type" => "application/json")
      req.body = body.to_json
      http.request(req)
    end

    if res.code == "429"
      wait = (JSON.parse(res.body)["retry_after_seconds"] || 60).to_i rescue 60
      Rails.cache.write("pingutil:backoff", true, expires_in: [wait, 1].max.seconds)
      return nil
    end
    Rails.logger.error("pingutil: API key rejected") if res.code == "401"
    res.is_a?(Net::HTTPSuccess) ? JSON.parse(res.body) : nil
  rescue Net::OpenTimeout, Net::ReadTimeout, SocketError, SystemCallError, OpenSSL::SSL::SSLError, JSON::ParserError
    nil
  end
end

# app/models/user.rb
class User < ApplicationRecord
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
  validates :email, pingutil_email: { mailbox: true }, on: :create
end

What to do with each result

pingutil resultAction in Ruby on Rails
verdict.is_spam: truerecord.errors.add(:email, :spam); the record does not save.
status: invalidrecord.errors.add(:email, :mailbox) with the did_you_mean hint when present.
status: risky or unknownLet the record save; gate rewards behind confirmation (for example Devise confirmable).
category: free, isp or companyStore it on the user to drive onboarding and sales routing.

Limits to plan for

  • Validators run synchronously in the request. The snippet uses a 1 s open timeout and 2 s or 5 s read timeouts and fails open on any error.
  • The test environment uses a null cache store by default, so the cached-category branch never triggers in tests unless you inject a memory store.
  • pingutil reports catch-all domains as risky and cannot confirm servers that refuse to answer. Per-account defaults are 60 requests a minute, 300 verified addresses and 2,000 lookups a day (3,000 and 30,000 a month). Those are Free plan limits; Enterprise has custom limits.

Ruby on Rails documentation

Ruby on Rails is a trademark of its owner. This integration uses Ruby on Rails's documented extension points; it is not an official Ruby on Rails app.

Common questions

Will this slow down my test suite?
Only if tests hit the network. Stub the HTTP calls with WebMock or inject a fake client; the validator is plain Ruby, so it is easy to replace in tests.
Should the check run on every save?
No. Use on: :create, and re-run it only when the email changes. Calling the API on every update spends budget and adds latency for no new information.

Stop bad addresses in Ruby on Rails today

Sign in with your email, create an API key and paste it into the step above. Test on a few real addresses first: the live demo shows exactly what your Ruby on Rails setup will receive.