Documentation

Ruby SDK

Ruby 3.0+
Bundler

Send emails with Ruby using the official Laneful Ruby SDK. Built for modern Ruby applications with comprehensive features and type safety.

Full Feature Support

Templates, attachments, tracking, webhooks

Modern Ruby

Ruby 3.0+ with modern syntax

Easy Integration

Simple API with comprehensive examples

Prerequisites

To get the most out of this guide, you'll need:

  • • Ruby 3.0 or higher
  • • Bundler (for dependency management)
  • • A Laneful account with API key
  • • Verified domain for sending emails

Installation

Bundler

Add the following to your Gemfile. This page describes version 1.3.0:

gem 'laneful-ruby', '~> 1.3', require: 'laneful'

Then run:

bundle install

Quick Start

Send your first email in minutes:

Send Simple Text Email

require 'laneful'

# Create client
client = Laneful::Client.new(
  'https://your-endpoint.z1.send.laneful.net',
  'your-auth-token'
)

begin
  # Create email (invalid input raises Laneful::ValidationException)
  email = Laneful::Email::Builder.new
    .from(Laneful::Address.new('sender@example.com', 'Your Name'))
    .to(Laneful::Address.new('recipient@example.com', 'Recipient Name'))
    .subject('Hello from Laneful!')
    .text_content('This is a simple test email sent using the Laneful Ruby SDK.')
    .build

  # Send email
  response = client.send_email(email)
  puts "✓ Email sent successfully!"
  puts "Response: #{response}"
rescue Laneful::ValidationException => e
  puts "✗ Validation error: #{e.message}"
rescue Laneful::ApiException => e
  puts "✗ API error: #{e.message}"
  puts "Status code: #{e.status_code}"
rescue Laneful::HttpException => e
  puts "✗ HTTP error: #{e.message}"
rescue StandardError => e
  puts "✗ Unexpected error: #{e.message}"
end

Replace https://your-endpoint.z1.send.laneful.net with your organization's own HTTP API endpoint and your-auth-token with a private API key, both available in the dashboard under Workspaces → Workspace Settings → API Keys (see Sending Email). The API is HTTPS-only.

Examples

Common use cases and patterns:

HTML Email with Tracking

# Create tracking settings (a flag you leave out is sent as false)
tracking = Laneful::TrackingSettings.new(
  opens: true,
  clicks: true,
  unsubscribes: true
)

email = Laneful::Email::Builder.new
  .from(Laneful::Address.new('sender@example.com'))
  .to(Laneful::Address.new('user@example.com'))
  .subject('HTML Email with Tracking')
  .html_content('<h1>Welcome!</h1><p>This is an <strong>HTML email</strong> with tracking enabled.</p>')
  .text_content('Welcome! This is an HTML email with tracking enabled.')
  .tracking(tracking)
  .tag('welcome-email')
  .build

response = client.send_email(email)

Template Email

# subject is required by the API, also with a template
email = Laneful::Email::Builder.new
  .from(Laneful::Address.new('sender@example.com'))
  .to(Laneful::Address.new('user@example.com'))
  .subject('Welcome to Acme Corporation')
  .template_id('welcome-template')
  .template_data({
    'name' => 'John Doe',
    'company' => 'Acme Corporation',
    'activation_link' => 'https://example.com/activate'
  })
  .build

response = client.send_email(email)

Email with Attachments

# Create attachment from file
attachment = Laneful::Attachment.from_file('/path/to/document.pdf')

email = Laneful::Email::Builder.new
  .from(Laneful::Address.new('sender@example.com'))
  .to(Laneful::Address.new('user@example.com'))
  .subject('Document Attached')
  .text_content('Please find the document attached.')
  .attachment(attachment)
  .build

response = client.send_email(email)

Multiple Recipients with Reply-To

email = Laneful::Email::Builder.new
  .from(Laneful::Address.new('sender@example.com', 'Your Name'))
  .to(Laneful::Address.new('user1@example.com', 'User One'))
  .to(Laneful::Address.new('user2@example.com', 'User Two'))
  .cc(Laneful::Address.new('cc@example.com', 'CC Recipient'))
  .bcc(Laneful::Address.new('bcc@example.com', 'BCC Recipient'))
  .reply_to(Laneful::Address.new('reply@example.com', 'Reply To'))
  .subject('Email to Multiple Recipients')
  .text_content('This email is being sent to multiple recipients.')
  .build

response = client.send_email(email)

Scheduled Email

# Schedule for 24 hours from now
send_time = Time.now.to_i + (24 * 60 * 60)

email = Laneful::Email::Builder.new
  .from(Laneful::Address.new('sender@example.com'))
  .to(Laneful::Address.new('user@example.com'))
  .subject('Scheduled Email')
  .text_content('This email was scheduled.')
  .send_time(send_time)
  .build

response = client.send_email(email)

Batch Email Sending

emails = [
  Laneful::Email::Builder.new
    .from(Laneful::Address.new('sender@example.com'))
    .to(Laneful::Address.new('user1@example.com'))
    .subject('Email 1')
    .text_content('First email content.')
    .build,
  Laneful::Email::Builder.new
    .from(Laneful::Address.new('sender@example.com'))
    .to(Laneful::Address.new('user2@example.com'))
    .subject('Email 2')
    .text_content('Second email content.')
    .build
]

response = client.send_emails(emails)

Webhook Handler Example

require 'sinatra'
require 'json'
require 'laneful'

# Complete webhook handler implementation
class WebhookController
  def initialize(webhook_secret)
    @webhook_secret = webhook_secret
  end

  def handle_webhook(request)
    begin
      # Extract signature from headers
      signature = Laneful::WebhookVerifier.extract_signature_from_headers(request.env)
      if signature.nil?
        return [401, { 'Content-Type' => 'application/json' }, { error: 'Missing signature' }.to_json]
      end

      # Get raw payload
      payload = request.body.read

      # Verify signature
      unless Laneful::WebhookVerifier.verify_signature(@webhook_secret, payload, signature)
        return [401, { 'Content-Type' => 'application/json' }, { error: 'Invalid signature' }.to_json]
      end

      # Parse and validate payload
      webhook_data = Laneful::WebhookVerifier.parse_webhook_payload(payload)

      # Process events
      webhook_data[:events].each do |event|
        event_type = event['event']
        email = event['email']

        case event_type
        when 'request'
          puts "Email accepted for: #{email}"
        when 'delivery'
          puts "Email delivered to: #{email}"
        when 'open'
          puts "Email opened by: #{email}"
        when 'click'
          url = event['url'] || 'Unknown URL'
          puts "Link clicked by #{email}: #{url}"
        when 'bounce'
          is_hard = event['is_hard'] || false
          puts "Email bounced (#{is_hard ? 'hard' : 'soft'}) for: #{email}"
        end
      end

      [200, { 'Content-Type' => 'application/json' }, { status: 'success' }.to_json]

    rescue ArgumentError => e
      [400, { 'Content-Type' => 'application/json' }, { error: "Invalid payload: #{e.message}" }.to_json]
    rescue StandardError => e
      [500, { 'Content-Type' => 'application/json' }, { error: "Processing error: #{e.message}" }.to_json]
    end
  end
end

controller = WebhookController.new(ENV.fetch('LANEFUL_WEBHOOK_SECRET'))

post '/webhooks/laneful' do
  controller.handle_webhook(request)
end

API Reference

Laneful::Client

Constructor

  • • Laneful::Client.new(base_url, auth_token, timeout: 30) - Create a new client instance (timeout in seconds)

Methods

  • • send_email(email, mail_settings = nil) - Send a single email; returns the JSON response as a Hash with string keys
  • • send_emails(emails, mail_settings = nil) - Send multiple emails in one request; returns the JSON response as a Hash with string keys

Laneful::Email::Builder

Required Fields

  • • from(address) - Sender address
  • • subject(subject) - Email subject. Always provide it, also when template_id is set: the API requires a subject, and build leaves that check to the API
  • • At least one to, cc or bcc, and text_content, html_content or template_id. build checks both for you and raises Laneful::ValidationException if either is missing

Optional Fields

  • • from_header(address) - Address for the visible From header, if it should differ from from
  • • to(address) - Recipient addresses
  • • cc(address) - CC addresses
  • • bcc(address) - BCC addresses
  • • text_content(content) - Plain text content
  • • html_content(content) - HTML content
  • • template_id(id) - Template ID
  • • template_data(data) - Template data
  • • attachment(attachment) - File attachments
  • • headers(headers) - Custom headers. Set From, To, Cc, Bcc, Reply-To and Subject with the builder methods and let Laneful generate the Message-ID; header entries for these are ignored (see Sending Email)
  • • reply_to(address) - Reply-to address
  • • send_time(time) - Scheduled send time (Unix timestamp)
  • • webhook_data(data) - Your own string key-value pairs, returned unchanged as metadata on every webhook event for this email (max 20 keys, keys up to 50 bytes, values up to 100 bytes in UTF-8)
  • • tag(tag) - Email tag for categorization
  • • tracking(tracking) - Tracking settings

Utility Classes

  • • Laneful::Address.new(email, name = nil) - Email address with optional name
  • • Laneful::Attachment.from_file(file_path) - Create attachment from file (read and Base64-encoded for you)
  • • Laneful::Attachment.new(filename, content_type, content, inline_id = nil) - Create attachment from raw data; content must be Base64-encoded, inline_id is for inline images
  • • Laneful::TrackingSettings.new(opens: false, clicks: false, unsubscribes: false, unsubscribe_group_id: nil, unsubscribe_group_name: nil) - Email tracking configuration and unsubscribe group (by ID or name). Tracking is on by default: without a tracking object, the API enables all three. When you pass one, set all three flags: they're always sent, so a flag you leave out turns that tracking off
  • • Laneful::MailSettings.new(sandbox_mode: nil, return_message_ids: nil, idempotency_key: nil) - Request-level settings for send_email and send_emails. With return_message_ids: true the response includes message_ids, each matching the message_id on that email's webhook events (every email must then have exactly one recipient). idempotency_key (1 to 36 bytes, 1.3.0 and later) prevents duplicate sends, see Error Handling. See Sending Email.

Laneful::WebhookVerifier

Signature Verification

  • • verify_signature(secret, payload, signature) - Verifies webhook signature (supports sha256= prefix). Returns false if the secret or signature is missing or empty
  • • generate_signature(secret, payload, include_prefix: false) - Generates signature for payload

Payload Processing

  • • parse_webhook_payload(payload) - Parse and validate webhook payload structure. Raises ArgumentError for the whole payload if any event is invalid. From 1.3.0, events of unknown types are kept and the empty lane_id of request events is accepted; earlier versions reject the whole payload
  • • signature_header_name - Get the correct header name for webhook signatures
  • • extract_signature_from_headers(headers) - Extract signature from HTTP headers. Pass the Rack env (request.env); keys are matched exactly (HTTP_X_WEBHOOK_SIGNATURE, X_WEBHOOK_SIGNATURE or x-webhook-signature)

parse_webhook_payload result (Hash)

  • • :is_batch - True if the body is a JSON array (batch mode), even with one event
  • • :events - The events as Hashes with string keys and every field Laneful sent, including id and metadata

Organization API Methods

  • • Unsubscribe groups: list_unsubscribe_groups(workspace_id, ...), create_unsubscribe_group(workspace_id, ...), update_unsubscribe_group(workspace_id, unsubscribe_group_id, ...)
  • • Domains: list_domains(workspace_id, ...), get_domain(workspace_id, domain), create_domain(workspace_id, ...), update_domain(workspace_id, domain, ...), verify_domain(workspace_id, domain), delete_domain(workspace_id, domain)
  • • Analytics: list_domain_spam_ratio_radar, list_google_postmaster_spam_reports, list_snds_reports

These methods call the Organization API, so create a separate client with base URL https://api.laneful.net and an Organization API key (see Organization API). Domain and unsubscribe group methods are scoped to a workspace and take workspace_id as their first argument (the API routes them under /v1/workspaces/{workspace_id}/...).

Error Handling

Comprehensive error handling with specific exception types:

begin
  email = Laneful::Email::Builder.new
    .from(Laneful::Address.new('sender@example.com'))
    .to(Laneful::Address.new('user@example.com'))
    .subject('Hello from Laneful!')
    .text_content('This is a test email.')
    .build

  response = client.send_email(email)
  puts "✓ Email sent successfully!"
  puts "Response: #{response}"
rescue Laneful::ValidationException => e
  # Invalid input data (raised by build, Address.new and Attachment.new)
  puts "✗ Validation error: #{e.message}"
  puts "Please check your email configuration"
rescue Laneful::ApiException => e
  # API returned an error
  puts "✗ API error: #{e.message}"
  puts "  Status code: #{e.status_code}"
  puts "  Error message: #{e.error_message}"
  puts "Please check your API credentials and endpoint"
rescue Laneful::HttpException => e
  # Network or HTTP-level error
  puts "✗ HTTP error: #{e.message}"
  puts "  Status code: #{e.status_code}"
  puts "Please check your network connection and endpoint URL"
rescue StandardError => e
  # Other unexpected errors
  puts "✗ Unexpected error: #{e.message}"
  puts e.backtrace
end

Exception Types

  • • Laneful::ValidationException - Input validation fails
  • • Laneful::ApiException - API returns error response
    Methods: status_code, error_message
  • • Laneful::HttpException - HTTP communication fails
    Methods: status_code
  • • Laneful::LanefulException - Base exception class

Best Practices

  • • Always wrap API calls in begin-rescue
  • • Handle specific exception types first
  • • Log errors with context information
  • • The SDK leaves retries to you. A send that timed out may already have been accepted, so when you retry it, reuse the same idempotency_key (see below)

Duplicate Send Protection

Pass an idempotency_key (1 to 36 bytes, see Sending Email) and reuse it when you retry a send, for example after a timeout:

response = client.send_email(
  email,
  Laneful::MailSettings.new(idempotency_key: "order-#{order_id}-receipt")
)

Laneful remembers a key per organization for one hour. A repeated request with the same key returns status accepted with no message IDs and sends nothing, even if the emails differ, so use a new key for every distinct send. Detection is best effort. A request that fails with HTTP 500 doesn't keep its key, so a retry with it is processed as a new request: before resending after a 500, check your webhook events (a request event means Laneful accepted the email). Sandbox mode requests aren't deduplicated. A key outside 1 to 36 bytes raises Laneful::ValidationException. Requires 1.3.0 or later.

Webhook Handling

Comprehensive webhook handling with signature verification, payload parsing, and validation:

  • • Verify the raw body (request.body.read) before parsing it: Laneful signs it with HMAC-SHA256 using your webhook secret and sends the hex digest, without a prefix, in the X-Webhook-Signature header. verify_signature also accepts a sha256= prefix and returns false without a secret.
  • • Return a 2xx within 30 seconds to acknowledge each webhook call; Laneful automatically retries any other outcome for up to 24 hours. Reserve 401 for a bad signature and 400 for a payload that can't be parsed, and answer 5xx when your handler fails.
  • • Use version 1.2.0 or later: it supports every event type Laneful sends, including request (earlier versions reject payloads that contain one). From 1.3.0, parse_webhook_payload also keeps events of unknown types; 1.2.0 rejects the whole payload, batch included, if any event type is unknown.
  • • Parsed events keep every field Laneful sends: use id (unique per event and unchanged on retries) to skip duplicates, and metadata to read back the email's webhook_data. See Webhooks for all fields.
  • • Use the default Laneful webhook format with parse_webhook_payload; it reads that format rather than the Mailgun or SendGrid formats.

Basic Signature Verification

# Rails controller; route: post '/webhooks/laneful', to: 'laneful_webhooks#create'
class LanefulWebhooksController < ActionController::API
  def create
    payload = request.body.read # Get the raw request body
    signature = request.headers['X-Webhook-Signature']
    secret = ENV.fetch('LANEFUL_WEBHOOK_SECRET')

    # Invalid signature
    return head :unauthorized unless Laneful::WebhookVerifier.verify_signature(secret, payload, signature)

    begin
      webhook_data = Laneful::WebhookVerifier.parse_webhook_payload(payload)
    rescue ArgumentError
      return head :bad_request
    end

    webhook_data[:events].each do |event|
      # Handle the event; an exception here answers 500, so Laneful retries
    end

    head :ok
  end
end

Advanced Webhook Processing

# Sinatra app
require 'sinatra'
require 'json'
require 'laneful'

webhook_secret = ENV.fetch('LANEFUL_WEBHOOK_SECRET')

# Complete webhook verification and processing workflow
post '/webhooks/laneful' do
  # Step 1: Get raw payload
  payload = request.body.read

  # Step 2: Extract signature from headers (X-Webhook-Signature)
  signature = Laneful::WebhookVerifier.extract_signature_from_headers(request.env)

  # Step 3: Verify signature over the raw payload
  unless signature && Laneful::WebhookVerifier.verify_signature(webhook_secret, payload, signature)
    halt 401, { error: 'Invalid webhook signature' }.to_json
  end

  # Step 4: Parse and validate payload structure
  begin
    webhook_data = Laneful::WebhookVerifier.parse_webhook_payload(payload)
  rescue ArgumentError => e
    halt 400, { error: "Invalid payload: #{e.message}" }.to_json
  end

  # Step 5: Process events (handles both batch and single event formats).
  # The handle_*_event helpers are yours; if one fails, answer 5xx so Laneful retries.
  begin
    webhook_data[:events].each do |event|
      case event['event']
      when 'request'
        handle_request_event(event)
      when 'delivery'
        handle_delivery_event(event)
      when 'open'
        handle_open_event(event)
      when 'click'
        handle_click_event(event)
      when 'bounce'
        handle_bounce_event(event)
      when 'drop'
        handle_drop_event(event)
      when 'spam_complaint'
        handle_spam_complaint_event(event)
      when 'unsubscribe'
        handle_unsubscribe_event(event)
      end
    end
  rescue StandardError => e
    halt 500, { error: "Processing error: #{e.message}" }.to_json
  end

  { status: 'success' }.to_json
end

Batch Mode Support

# payload: the raw request body, after its signature has been verified
webhook_data = Laneful::WebhookVerifier.parse_webhook_payload(payload)

if webhook_data[:is_batch]
  # Batch mode: the body is a JSON array of events
  puts "Processing #{webhook_data[:events].length} events in batch"
else
  # Processing single event
  puts "Processing single event"
end

# Process all events
webhook_data[:events].each do |event|
  process_event(event)
end

Supported Webhook Events

Delivery Events

  • • request - Email accepted and queued for delivery
  • • delivery - Email delivered successfully
  • • bounce - Email bounced (hard or soft)
  • • drop - Email dropped (spam, invalid, etc.)
  • • spam_complaint - Recipient marked email as spam

Engagement Events

  • • open - Email opened by recipient
  • • click - Link clicked in email
  • • unsubscribe - Recipient unsubscribed

Webhook Features

Security

  • • HMAC-SHA256 signature verification
  • • Bare hex signatures, as Laneful sends them (a sha256= prefix is also accepted)
  • • Constant-time comparison (timing attack protection)
  • • Multiple header format support

Validation

  • • JSON payload structure validation
  • • Required field validation
  • • Email format validation

Ready to Get Started?

Start sending emails with Ruby in minutes. Check out the examples and integrate with your application.