Receive Email Webhooks in Rails

Complete guide to integrating JsonHook with Rails (Ruby). Working code examples for webhook handling, signature verification, and payload parsing.

Table of Contents
  1. Quick Start: Rails Email Webhook
  2. Full Rails Implementation
  3. Parsing the Webhook Payload
  4. Verifying Webhook Signatures
  5. Error Handling Best Practices
  6. Rails Framework Tips

Quick Start: Rails Email Webhook

JsonHook delivers every inbound email as a JSON POST request to your webhook endpoint. Setting up a Rails handler takes less than 5 minutes. Start by initializing your project:

rails new webhook-app --api && cd webhook-app

Then create your webhook endpoint. The following example shows the minimal code needed to receive and acknowledge a JsonHook delivery:

# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def receive
    payload = JSON.parse(request.raw_post)
    email   = payload['email']
    Rails.logger.info "Email from #{email['from']}: #{email['subject']}"
    head :ok
  end
end

# config/routes.rb
# post '/webhook', to: 'webhooks#receive'

Point your JsonHook address webhook URL to this endpoint and you will start receiving parsed emails as JSON within seconds of the email arriving.

Full Rails Implementation

The quick start example above is enough to get started, but a production implementation should include signature verification, structured error handling, and proper HTTP response codes. The complete example below demonstrates all of these patterns together.

This implementation verifies the X-JsonHook-Signature header to confirm the request genuinely came from JsonHook, parses the full email payload, and returns the appropriate HTTP status codes to trigger or suppress retries.

# app/controllers/webhooks_controller.rb
class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  WEBHOOK_SECRET = ENV['JSONHOOK_WEBHOOK_SECRET']

  def receive
    raw_body  = request.raw_post
    signature = request.headers['X-JsonHook-Signature']

    unless valid_signature?(raw_body, signature)
      Rails.logger.warn 'Invalid JsonHook signature'
      render json: { error: 'Unauthorized' }, status: :unauthorized and return
    end

    payload   = JSON.parse(raw_body)
    email     = payload['email']
    timestamp = payload['timestamp']
    address   = payload['address']

    Rails.logger.info "[#{timestamp}] Email at #{address} from #{email['from']}"
    Rails.logger.info "Subject: #{email['subject']}"

    (email['attachments'] || []).each do |att|
      Rails.logger.info "Attachment: #{att['filename']} (#{att['size']} bytes)"
    end

    # Queue processing with Active Job
    # ProcessEmailJob.perform_later(payload)

    head :ok
  end

  private

  def valid_signature?(raw_body, sig_header)
    return false if sig_header.blank?
    computed = OpenSSL::HMAC.hexdigest('SHA256', WEBHOOK_SECRET, raw_body)
    ActiveSupport::SecurityUtils.secure_compare(computed, sig_header)
  end
end

The webhook handler returns 200 immediately after queuing the email for processing. Avoid doing expensive work (database writes, API calls) synchronously inside the handler — process the payload in a background job to stay within JsonHook's 10-second response timeout.

Build Your Rails Email Integration

Free API key — start receiving webhooks in 5 minutes.

Get Free API Key

Parsing the Webhook Payload

Every JsonHook delivery is an HTTP POST with Content-Type: application/json. The payload follows a consistent schema regardless of the originating email client or provider:

raw_body = request.raw_post
payload  = JSON.parse(raw_body)

event     = payload['event']      # "email.received"
timestamp = payload['timestamp']
address   = payload['address']

email     = payload['email']
from      = email['from']         # "Alice "
to        = email['to']           # Array of strings
subject   = email['subject']
text_body = email['textBody']
html_body = email['htmlBody']

(email['attachments'] || []).each do |att|
  puts "#{att['filename']} (#{att['contentType']}, #{att['size']} bytes)"
end

Key fields in the payload:

  • event — Always "email.received" for inbound email events
  • timestamp — ISO 8601 timestamp of when JsonHook received the email
  • address — The JsonHook inbound address that received the email (e.g., [email protected])
  • email.from — Sender address string, e.g., "Alice <[email protected]>"
  • email.to — Array of recipient address strings
  • email.subject — Email subject line
  • email.textBody — Plain text body of the email (may be empty if HTML-only)
  • email.htmlBody — HTML body of the email (may be empty if plain-text-only)
  • email.attachments — Array of attachment objects, each with filename, contentType, size, and contentId

Verifying Webhook Signatures

JsonHook signs every webhook delivery using HMAC-SHA256. The signature is included in the X-JsonHook-Signature request header as a hex digest. To verify it, compute the HMAC-SHA256 of the raw request body using your address's webhook secret and compare it to the header value.

Your webhook secret is returned when you create an inbound address via the API (POST /api/addresses). Store it as an environment variable — never hard-code it.

require 'openssl'

def valid_signature?(raw_body, sig_header)
  return false if sig_header.blank? || WEBHOOK_SECRET.blank?
  computed = OpenSSL::HMAC.hexdigest('SHA256', WEBHOOK_SECRET, raw_body)
  # ActiveSupport::SecurityUtils.secure_compare is constant-time
  ActiveSupport::SecurityUtils.secure_compare(computed, sig_header)
end

# Usage:
# raw_body  = request.raw_post
# sig       = request.headers['X-JsonHook-Signature']
# unless valid_signature?(raw_body, sig)
#   render json: { error: 'Unauthorized' }, status: :unauthorized and return
# end

Always verify the signature before processing the payload. Return 401 for invalid signatures so that legitimate retries from JsonHook (which always include a valid signature) are distinguishable from spoofed requests.

Error Handling Best Practices

Reliable webhook handling requires careful attention to error responses. JsonHook uses your HTTP response code to decide whether to retry a delivery:

  • Return 200 quickly: Acknowledge receipt immediately and process asynchronously. JsonHook will retry any non-2xx response.
  • Return 400 for bad requests: If the payload fails your own validation (not signature — use 401 for that), return 400 to prevent retries of malformed deliveries.
  • Return 500 to trigger retries: If your downstream system is temporarily unavailable, returning 500 causes JsonHook to retry with exponential backoff (up to 5 attempts over ~1 hour).
  • Never return 200 before verifying the signature: Doing so silently accepts spoofed requests.

Rails-specific tips:

  • Add skip_before_action :verify_authenticity_token to your webhooks controller — Rails' CSRF protection will block external POST requests without it
  • Use request.raw_post rather than params or request.body.read to get the original raw request body for HMAC verification
  • Use ActiveSupport::SecurityUtils.secure_compare for constant-time signature comparison — it is available in all modern Rails versions
  • Use Active Job with Sidekiq (ProcessEmailJob.perform_later(payload)) to process the email asynchronously and call head :ok immediately in the controller action

Rails Framework Tips

Rails provides several conveniences that make webhook handling cleaner. Here are framework-specific patterns to use when integrating JsonHook:

  • Register your webhook route before any authentication middleware — the JsonHook request does not carry user credentials, only the HMAC signature.
  • Use raw body access for signature verification. Many Rails frameworks parse the body automatically — make sure you are hashing the raw bytes, not the re-serialized parsed object.
  • Use a dedicated route or controller file for webhook handlers to keep the codebase organized as you add more inbound address integrations.
  • Log the address field from every payload to track which inbound address received the email — useful for multi-address setups.
  • Consider using Rails's built-in request validation or a schema library (e.g., Zod, Pydantic, etc.) to validate the payload structure after signature verification.

Frequently Asked Questions

How do I receive JsonHook webhooks in Rails?
Create an HTTP endpoint in your Rails application that accepts POST requests with a JSON body. Register the endpoint URL in your JsonHook inbound address configuration. When email arrives at your JsonHook address, JsonHook will POST the parsed email as JSON to your endpoint. See the complete code example on this page for a production-ready implementation including signature verification.
Does JsonHook work with Rails?
Yes. JsonHook works with any HTTP server that can receive POST requests — Rails is fully supported. JsonHook delivers a standard application/json POST with an HMAC-SHA256 signature header. There is no SDK or library required; you use your language or framework's standard HTTP and crypto libraries.
How do I verify webhook signatures in Rails?
Read the raw request body bytes before any JSON parsing, then compute HMAC-SHA256 of those bytes using your webhook secret as the key. Compare the resulting hex digest to the value of the X-JsonHook-Signature header. Use a constant-time comparison function to prevent timing attacks. Return 401 if the signatures do not match. The full code example is shown in the "Verifying Webhook Signatures" section above.
What does the JsonHook payload look like in Rails?
The payload is a JSON object with an event string ("email.received"), a timestamp ISO string, an address string (the receiving JsonHook address), and an email object containing from, to, subject, textBody, htmlBody, and attachments. In Rails, parse it with your standard JSON library and access fields as you would any JSON object. See the "Parsing the Webhook Payload" section for a complete example.