Skip to content

sendpost/ruby-esp-example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SendPost Ruby SDK - ESP Example

This project provides a comprehensive example demonstrating how Email Service Providers (ESPs) can use the SendPost Ruby SDK to manage email sending operations.

Overview

The example demonstrates a complete ESP workflow including:

  1. Sub-Account Management - Create and manage sub-accounts for different clients or use cases
  2. Webhook Setup - Configure webhooks to receive real-time email event notifications
  3. Domain Management - Add and verify sending domains
  4. Email Sending - Send transactional and marketing emails
  5. Message Tracking - Retrieve message details for tracking and debugging
  6. Statistics & Analytics - Monitor email performance via sub-account stats, IP stats, and IP pool stats
  7. IP Pool Management - Create and manage IP pools for better deliverability control

Prerequisites

  • Ruby 2.7 or higher
  • Bundler (Ruby gem manager)
  • SendPost account with:
    • Account API Key (for account-level operations)
    • Sub-Account API Key (for sub-account-level operations)

Setup

1. Clone or Download the Project

cd example-sdk-ruby

2. Install Dependencies

Install the required dependencies using Bundler:

bundle install

This will install the SendPost Ruby SDK version 2.0.0 from RubyGems.org.

Or install the SendPost Ruby SDK directly:

gem install sendpost_ruby_sdk

3. Configure API Keys

You can set API keys in two ways:

Option A: Environment Variables (Recommended)

export SENDPOST_ACCOUNT_API_KEY="your_account_api_key_here"
export SENDPOST_SUB_ACCOUNT_API_KEY="your_sub_account_api_key_here"

Option B: Edit the Source Code

Edit ESPExample.rb and update the constants:

SUB_ACCOUNT_API_KEY = "your_sub_account_api_key_here"
ACCOUNT_API_KEY = "your_account_api_key_here"

4. Update Configuration Values

Edit ESPExample.rb and update:

  • TEST_FROM_EMAIL - Your verified sender email address
  • TEST_TO_EMAIL - Recipient email address
  • TEST_DOMAIN_NAME - Your sending domain
  • WEBHOOK_URL - Your webhook endpoint URL

Running the Example

Run the Complete Workflow

ruby ESPExample.rb

Or if using Bundler:

bundle exec ruby ESPExample.rb

This will execute the complete ESP workflow demonstrating all features.

Project Structure

example-sdk-ruby/
├── ESPExample.rb          # Main example class
├── README.md              # This file
├── Gemfile                # Ruby dependencies
└── .gitignore             # Git ignore file (optional)

Workflow Steps

The example demonstrates the following workflow:

Step 1: Sub-Account Management

  • List all sub-accounts
  • Create new sub-accounts for different clients or use cases

Step 2: Webhook Configuration

  • Create webhooks to receive email event notifications
  • Configure which events to receive (delivered, opened, clicked, bounced, etc.)

Step 3: Domain Management

  • Add sending domains
  • View DNS records needed for domain verification
  • List all domains

Step 4: Email Sending

  • Send transactional emails (order confirmations, receipts, etc.)
  • Send marketing emails (newsletters, promotions, etc.)
  • Configure tracking (opens, clicks)
  • Add custom headers and fields

Step 5: Message Tracking

  • Retrieve message details by message ID
  • View delivery information, IP used, submission time, etc.

Step 6: Statistics & Analytics

  • Get sub-account statistics (processed, delivered, opens, clicks, bounces, etc.)
  • Get aggregate statistics
  • Get account-level statistics across all sub-accounts

Step 7: IP and IP Pool Management

  • List all dedicated IPs
  • Create IP pools for better deliverability control
  • View IP pool configurations

Key Features Demonstrated

Email Sending

  • Transactional Emails: Order confirmations, receipts, notifications
  • Marketing Emails: Newsletters, promotions, campaigns
  • Tracking: Open tracking, click tracking
  • Customization: Custom headers, custom fields, groups

Statistics & Monitoring

  • Sub-Account Stats: Daily statistics for a specific sub-account
  • Aggregate Stats: Overall performance metrics
  • Account Stats: Statistics across all sub-accounts
  • Performance Metrics: Open rates, click rates, delivery rates

Infrastructure Management

  • Sub-Accounts: Organize sending by client, product, or use case
  • Domains: Add and verify sending domains
  • IPs: Monitor dedicated IP addresses
  • IP Pools: Group IPs for better deliverability control

Event Handling

  • Webhooks: Receive real-time notifications for email events
  • Event Types: Processed, delivered, dropped, bounced, opened, clicked, unsubscribed, spam

API Keys Explained

Account API Key (X-Account-ApiKey)

Used for account-level operations:

  • Creating and managing sub-accounts
  • Managing IPs and IP pools
  • Creating webhooks
  • Getting account-level statistics
  • Retrieving messages

Sub-Account API Key (X-SubAccount-ApiKey)

Used for sub-account-level operations:

  • Sending emails
  • Managing domains
  • Managing suppressions
  • Getting sub-account statistics

Example Output

When you run the example, you'll see output like:

╔═══════════════════════════════════════════════════════════════╗
║   SendPost Ruby SDK - ESP Example Workflow                    ║
╚═══════════════════════════════════════════════════════════════╝

=== Step 1: Listing All Sub-Accounts ===
Retrieving all sub-accounts...
✓ Retrieved 3 sub-account(s)
  - ID: 50441
    Name: API
    API Key: pR0YIuxYSbVwmQi2Y8Qs
    ...

=== Step 2: Creating Webhook ===
Creating webhook...
  URL: https://your-webhook-endpoint.com/webhook
✓ Webhook created successfully!
  ID: 12345
  ...

...

Error Handling

The example includes comprehensive error handling. If an operation fails, you'll see:

  • HTTP status code
  • Error response body
  • Stack trace for debugging

Common issues:

  • 401 Unauthorized: Invalid or missing API key
  • 403 Forbidden: Resource already exists or insufficient permissions
  • 404 Not Found: Resource ID doesn't exist
  • 422 Unprocessable Entity: Invalid request body or parameters

Ruby SDK Installation

Install from RubyGems (Recommended)

The SendPost Ruby SDK is available on RubyGems.org. Install the latest version (2.0.0) with:

gem install sendpost_ruby_sdk

Or add to your Gemfile:

gem 'sendpost_ruby_sdk', '~> 2.0.0'

Install from Source

If you're using the SDK from the local repository:

cd ../sendpost-ruby-sdk
gem build sendpost_ruby_sdk.gemspec
gem install ./sendpost_ruby_sdk-2.0.0.gem

Or add to your Gemfile:

gem 'sendpost_ruby_sdk', path: '../sendpost-ruby-sdk'

Verify Installation

require 'sendpost_ruby_sdk'
puts Sendpost::VERSION

Code Examples

Basic Email Sending

require 'sendpost_ruby_sdk'

# Configure API key
config = Sendpost::Configuration.new
config.host = 'https://api.sendpost.io/api/v1'
config.api_key['X-SubAccount-ApiKey'] = 'your_sub_account_api_key'

# Create API client
api_client = Sendpost::ApiClient.new(config)
email_api = Sendpost::EmailApi.new(api_client)

# Create email message
email_message = Sendpost::EmailMessageObject.new

# Set sender
from_addr = Sendpost::EmailMessageFrom.new
from_addr.email = 'sender@example.com'
from_addr.name = 'Sender'
email_message.from = from_addr

# Set recipient
recipient = Sendpost::EmailMessageToInner.new
recipient.email = 'recipient@example.com'
recipient.name = 'Recipient'
email_message.to = [recipient]

# Set email content
email_message.subject = 'Test Email'
email_message.html_body = '<h1>Hello!</h1>'
email_message.text_body = 'Hello!'

# Send email
response = email_api.send_email(email_message)
puts "Message ID: #{response[0].message_id}"

Getting Statistics

require 'sendpost_ruby_sdk'
require 'date'

# Configure API key
config = Sendpost::Configuration.new
config.host = 'https://api.sendpost.io/api/v1'
config.api_key['X-Account-ApiKey'] = 'your_account_api_key'

# Create API client
api_client = Sendpost::ApiClient.new(config)
stats_api = Sendpost::StatsApi.new(api_client)

# Get stats for last 7 days
to_date = Date.today
from_date = to_date - 7

stats = stats_api.account_subaccount_stat_subaccount_id_get(
  from_date, to_date, sub_account_id
)

stats.each do |stat|
  puts "Date: #{stat.date}, Processed: #{stat.stats.processed}"
end

Ruby-Specific Notes

Configuration

The Ruby SDK uses a configuration object pattern:

config = Sendpost::Configuration.new
config.host = 'https://api.sendpost.io/api/v1'
config.api_key['X-SubAccount-ApiKey'] = 'your_key'

API Client Pattern

Each API class requires an ApiClient instance:

api_client = Sendpost::ApiClient.new(config)
email_api = Sendpost::EmailApi.new(api_client)

Error Handling

The SDK raises Sendpost::ApiError for API errors:

begin
  response = email_api.send_email(email_message)
rescue Sendpost::ApiError => e
  puts "Error: #{e.code} - #{e.response_body}"
rescue StandardError => e
  puts "Unexpected error: #{e.message}"
end

Next Steps

After running the example:

  1. Customize for Your Use Case: Modify the example to match your specific requirements
  2. Integrate with Your Application: Use the SDK in your own Ruby application
  3. Set Up Webhooks: Configure your webhook endpoint to receive email events
  4. Monitor Statistics: Set up regular monitoring of your email performance
  5. Optimize Deliverability: Use IP pools and domain verification to improve deliverability

Additional Resources

Support

For questions or issues:

License

This example is provided as-is for demonstration purposes.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages