Skip to content

Official Ruby SDK for GetMailer - Modern email delivery for developers

Notifications You must be signed in to change notification settings

getplatform/getmailer-ruby

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 

Repository files navigation

GetMailer Ruby SDK

Official Ruby client library for the GetMailer email service platform.

Installation

Add to your Gemfile:

gem 'getmailer'

Or install directly:

gem install getmailer

Quick Start

require 'getmailer'

# Configure globally
Getmailer.configure do |config|
  config.api_key = 'your-api-key'
  config.base_url = 'https://api.getmailer.dev'  # Optional
end

# Send an email
Getmailer.send_email(
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Hello from GetMailer',
  html: '<h1>Hello!</h1><p>Welcome to GetMailer.</p>'
)

Client Instantiation

You can also create client instances directly:

client = Getmailer::Client.new(
  api_key: 'your-api-key',
  base_url: 'https://api.getmailer.dev',  # Optional
  timeout: 30  # Optional, seconds
)

Sending Emails

Single Email

result = client.emails.send(
  to: 'recipient@example.com',
  from: 'sender@yourdomain.com',
  subject: 'Hello!',
  html: '<h1>Hello World</h1>',
  text: 'Hello World',
  reply_to: 'replies@yourdomain.com',
  tags: ['welcome', 'onboarding'],
  metadata: { user_id: '123' }
)

puts result['id']  # Email ID

Multiple Recipients

client.emails.send(
  to: ['user1@example.com', 'user2@example.com'],
  from: 'sender@yourdomain.com',
  subject: 'Team Update',
  html: '<p>Important update...</p>'
)

Batch Sending

result = client.emails.send_batch([
  {
    to: 'user1@example.com',
    from: 'sender@yourdomain.com',
    subject: 'Personalized for User 1',
    html: '<p>Hello User 1!</p>'
  },
  {
    to: 'user2@example.com',
    from: 'sender@yourdomain.com',
    subject: 'Personalized for User 2',
    html: '<p>Hello User 2!</p>'
  }
])

puts result['batchId']

Scheduled Emails

# Schedule for later
require 'time'

client.emails.schedule(
  email_id,
  send_at: (Time.now + 3600).iso8601  # 1 hour from now
)

# Cancel scheduled email
client.emails.cancel(email_id)

Domain Management

# List domains
domains = client.domains.list
domains['domains'].each { |d| puts d['domain'] }

# Add domain
result = client.domains.create(domain: 'mail.example.com')
puts result['dnsRecords']  # DNS records to configure

# Verify domain
client.domains.verify(domain_id)

# Get DMARC report
report = client.domains.dmarc_report(domain_id)

Templates

# Create template
template = client.templates.create(
  name: 'Welcome Email',
  subject: 'Welcome, {{name}}!',
  html: '<h1>Hello {{name}}</h1><p>Welcome to our platform.</p>'
)

# Render template
rendered = client.templates.render(
  template['id'],
  variables: { name: 'John' }
)
puts rendered['html']

# Send with template
client.emails.send(
  to: 'user@example.com',
  from: 'hello@yourdomain.com',
  template_id: template['id'],
  variables: { name: 'John' }
)

Audiences & Contacts

# Create audience
audience = client.audiences.create(name: 'Newsletter Subscribers')

# Add contact
client.audiences.add_contact(
  audience['id'],
  email: 'subscriber@example.com',
  first_name: 'John',
  last_name: 'Doe',
  custom_fields: { plan: 'premium' }
)

# List contacts
contacts = client.audiences.contacts(audience['id'])

# Get engagement stats
stats = client.audiences.engagement_stats(audience['id'])

Webhooks

Available Event Types

# Use the constant for local validation
Getmailer::Resources::Webhooks::EVENTS
# => ['SENT', 'DELIVERED', 'OPENED', 'CLICKED', 'BOUNCED', 'COMPLAINED', 'FAILED']

# Or fetch from API (source of truth)
event_types = client.webhooks.event_types
puts event_types['email']       # Email events
puts event_types['automation']  # Automation events
puts event_types['all']         # All events

Managing Webhooks

# Create webhook
webhook = client.webhooks.create(
  url: 'https://yourapp.com/webhooks/getmailer',
  events: ['DELIVERED', 'BOUNCED', 'COMPLAINED']
)

puts webhook['signingSecret']  # Store this securely!

# List webhooks
client.webhooks.list

# Get delivery history
client.webhooks.deliveries(webhook['id'])

Verifying Webhook Signatures

# In your webhook handler (e.g., Rails controller)
class WebhooksController < ApplicationController
  skip_before_action :verify_authenticity_token

  def handle
    payload = request.body.read
    signature = request.headers['X-Getmailer-Signature']
    timestamp = request.headers['X-Getmailer-Timestamp']

    begin
      event = Getmailer::Resources::Webhooks.construct_event(
        payload: payload,
        signature: signature,
        timestamp: timestamp,
        secret: ENV['GETMAILER_WEBHOOK_SECRET']
      )

      case event['type']
      when 'DELIVERED'
        handle_delivered(event['data'])
      when 'BOUNCED'
        handle_bounce(event['data'])
      end

      head :ok
    rescue Getmailer::ValidationError
      head :bad_request
    end
  end
end

Suppression List

# Add to suppression list
client.suppression.add(
  email: 'bounced@example.com',
  reason: 'hard_bounce'
)

# Check if suppressed
result = client.suppression.check('test@example.com')
puts result['suppressed']

# Remove from suppression
client.suppression.remove('test@example.com')

A/B Testing

# Create subject line test
experiment = client.experiments.create(
  name: 'Welcome Email Subject Test',
  type: 'subject',
  variants: [
    { name: 'A', subject: 'Welcome to our platform!' },
    { name: 'B', subject: 'Get started with your new account' }
  ],
  traffic_percentage: 100,
  winning_metric: 'open_rate',
  auto_select_winner: true,
  duration_hours: 48
)

# Start experiment
client.experiments.start(experiment['id'])

# Get results
results = client.experiments.results(experiment['id'])
puts "Winner: #{results['winner']}"
puts "Statistical significance: #{results['significance']}"

Email Validation

# Validate single email
result = client.validation.validate('test@example.com')
puts result['valid']      # true/false
puts result['score']      # 0-100 risk score
puts result['risk']       # low/medium/high
puts result['reason']     # Reason if invalid

# Batch validation
results = client.validation.validate_batch([
  'valid@example.com',
  'invalid@fake.com'
])

# Client-side validation (no API call)
Getmailer::Resources::Validation.valid_syntax?('test@example.com')  # true
Getmailer::Resources::Validation.disposable?('test@tempmail.com')   # true
Getmailer::Resources::Validation.role_account?('admin@example.com') # true

Monitoring & Analytics

# System health
health = client.monitoring.health
puts health['status']

# Email statistics
stats = client.monitoring.stats(days: 30)
puts "Sent: #{stats['sent']}"
puts "Delivered: #{stats['delivered']}"
puts "Bounced: #{stats['bounced']}"

# Reputation
reputation = client.monitoring.reputation
puts "Score: #{reputation['score']}"

# Analytics
analytics = client.monitoring.analytics(
  start_date: Date.today - 7,
  end_date: Date.today
)

Error Handling

begin
  client.emails.send(
    to: 'invalid-email',
    from: 'sender@example.com',
    subject: 'Test'
  )
rescue Getmailer::AuthenticationError => e
  puts "Authentication failed: #{e.message}"
rescue Getmailer::ValidationError => e
  puts "Validation error: #{e.message}"
  puts "Details: #{e.response_body}"
rescue Getmailer::RateLimitError => e
  puts "Rate limited. Retry after: #{e.retry_after} seconds"
rescue Getmailer::NotFoundError => e
  puts "Resource not found: #{e.message}"
rescue Getmailer::ServerError => e
  puts "Server error: #{e.message}"
rescue Getmailer::NetworkError => e
  puts "Network error: #{e.message}"
end

Configuration Options

Getmailer.configure do |config|
  # Required
  config.api_key = ENV['GETMAILER_API_KEY']

  # Optional
  config.base_url = 'https://api.getmailer.dev'  # Custom API URL
end

# Or via environment variables
# GETMAILER_API_KEY=your-key
# GETMAILER_BASE_URL=https://api.getmailer.dev

Rails Integration

Add to config/initializers/getmailer.rb:

Getmailer.configure do |config|
  config.api_key = Rails.application.credentials.getmailer_api_key
end

Use in your application:

class UserMailer
  def welcome(user)
    Getmailer.send_email(
      to: user.email,
      from: 'welcome@yourapp.com',
      subject: "Welcome, #{user.name}!",
      html: render_to_string('welcome', locals: { user: user })
    )
  end
end

Thread Safety

The client is thread-safe. You can share a single instance across threads:

# config/initializers/getmailer.rb
GETMAILER_CLIENT = Getmailer::Client.new(api_key: ENV['GETMAILER_API_KEY'])

# Anywhere in your app
GETMAILER_CLIENT.emails.send(...)

License

MIT

About

Official Ruby SDK for GetMailer - Modern email delivery for developers

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •  

Languages