Skip to content

Latest commit

 

History

History

ruby-elasticemail-examples

Folders and files

README.md

Ruby Email API Examples - Elastic Email

Send transactional and bulk email from Ruby with the Elastic Email email API. Standalone scripts plus two web applications - Sinatra and Rails - built on the official Elastic Email Ruby SDK.

First time here? The Ruby quickstart gets you from nothing to a delivered email in five minutes. For the concepts behind these examples, see the Elastic Email guides.

Versions: Elastic Email REST API v4 · SDK ElasticEmail ~> 4.4 (RubyGems) · Ruby 3.1+ · Sinatra 4, Rails 7.2

Prerequisites

Installation

# Install dependencies
bundle install

# Copy environment variables
cp .env.example .env

# Add your Elastic Email API key to .env

Standalone Examples

Run every script from this folder. All scripts load examples/ee.rb, which reads .env, configures the SDK and exits early when ELASTICEMAIL_API_KEY is missing.

Basic Email Sending

ruby examples/basic_send.rb

Bulk Sending

ruby examples/batch_send.rb

With Attachments

ruby examples/with_attachments.rb

With CID (Inline) Attachments

ruby examples/with_cid_attachments.rb

Using Templates

ruby examples/with_template.rb

Scheduled Sending

ruby examples/scheduled_send.rb

Prevent Gmail Threading

ruby examples/prevent_threading.rb

Contacts and Lists

ruby examples/contacts.rb

Domain Management

ruby examples/domains.rb

Email Status

ruby examples/email_status.rb <transactionId> [messageId]

Webhooks

ruby examples/webhooks.rb

Creates a signed webhook (EnableSigning: true, DeliveryMethod: "PostJson"), prints its SigningSecret once, rotates the secret, then deletes the webhook. Store the secret as ELASTICEMAIL_WEBHOOK_SECRET so the /webhook handlers verify each request.

Inbound Routes

ruby examples/inbound.rb

Double Opt-In

# Subscribe (creates contact + sends confirmation)
ruby examples/double_optin/subscribe.rb user@example.com "John Doe"

# Click-tracking based confirmation server
ruby examples/double_optin/webhook.rb

Suppressions

ruby examples/suppressions.rb [email]

Email Verification

ruby examples/email_verification.rb someone@example.com

Statistics

ruby examples/statistics.rb

Sub-Accounts

ruby examples/sub_accounts.rb
# Creating a sub-account affects billing:
CREATE_SUBACCOUNT=true ruby examples/sub_accounts.rb

Sinatra Application

ruby sinatra_app/app.rb

# Then in another terminal:
curl -X POST http://localhost:3000/send \
  -H "Content-Type: application/json" \
  -d '{"to": "you@yourdomain.com", "subject": "Hello", "message": "Hi from Sinatra!"}'

Rails Application

cd rails_app
bundle install
bundle exec rails server -p 3000

curl -X POST http://localhost:3000/send \
  -H "Content-Type: application/json" \
  -d '{"to": "you@yourdomain.com", "subject": "Hello", "message": "Hi from Rails!"}'

See rails_app/README.md for details.

API Endpoints

Both server apps expose the same routes and JSON shapes.

  • GET /health -> {"status": "ok"}
  • POST /send body {"to", "subject", "message"} -> {"success": true, "transactionId", "messageId"}; an optional Idempotency-Key request header is forwarded to Elastic Email (a new key is generated otherwise), so clients can retry safely with the same key
  • GET|POST /webhook - Elastic Email event notifications (status, to, transaction, messageid, target, ...). Recommended: create the webhook with EnableSigning: true and DeliveryMethod: "PostJson" and set ELASTICEMAIL_WEBHOOK_SECRET; each event then arrives as a POST with a JSON body and X-ElasticEmail-Timestamp / X-ElasticEmail-Signature headers, and the handler rejects requests with a missing, wrong or older-than-5-minutes signature with 401. Fallback for unsigned webhooks (secret not set): add ?token=... matching ELASTICEMAIL_WEBHOOK_TOKEN to the URL; events then arrive as GET with the details in the query string.
  • POST /inbound?token=... - inbound email pushed by an inbound route (from_email, subject, body_html, att1_name, att1_content, ...). Forwards a copy to CONTACT_EMAIL.
  • POST /double-optin/subscribe body {"email", "name"} - stores the contact as Transactional and sends a confirmation link
  • GET /double-optin/confirm?email=&token= - verifies the HMAC token and adds the contact to ELASTICEMAIL_LIST_NAME
  • GET|POST /double-optin/webhook - confirms on a Clicked event whose target is the confirm link. Verified like /webhook (signature, or ?token= for unsigned webhooks).

Failures return {"error": "<message from the API>"} with the API status code.

Quick Usage

require "ElasticEmail"

ElasticEmail.configure do |config|
  config.api_key["X-ElasticEmail-ApiKey"] = ENV.fetch("ELASTICEMAIL_API_KEY")
end

result = ElasticEmail::EmailsApi.new.emails_transactional_post(
  ElasticEmail::EmailTransactionalMessageData.new(
    recipients: ElasticEmail::TransactionalRecipient.new(to: ["you@yourdomain.com"]),
    content: ElasticEmail::EmailContent.new(
      from: "Acme <hello@yourdomain.com>",
      subject: "Hello",
      body: [ElasticEmail::BodyPart.new(content_type: "HTML", content: "<p>Hello World</p>")]
    )
  )
)

puts result.transaction_id, result.message_id

Errors raise ElasticEmail::ApiError with code (HTTP status) and response_body ({"Error": "..."}).

Project Structure

ruby-elasticemail-examples/
├── examples/
│   ├── ee.rb                     # Shared config (API key, env values, error helper)
│   ├── basic_send.rb             # Simple transactional email
│   ├── batch_send.rb             # Bulk send with merge fields
│   ├── with_attachments.rb       # Emails with files
│   ├── with_cid_attachments.rb   # Inline images
│   ├── with_template.rb          # Templates with merge values
│   ├── scheduled_send.rb         # Delayed delivery (TimeOffset)
│   ├── prevent_threading.rb      # Prevent Gmail threading
│   ├── contacts.rb               # Contacts and lists
│   ├── domains.rb                # Domain verification
│   ├── email_status.rb           # Delivery status by transaction id
│   ├── webhooks.rb               # Manage webhooks
│   ├── inbound.rb                # Manage inbound routes
│   ├── double_optin/
│   │   ├── subscribe.rb          # Double opt-in: subscribe
│   │   └── webhook.rb            # Double opt-in: click-based confirm server
│   ├── suppressions.rb           # Unsubscribes, bounces, complaints
│   ├── email_verification.rb     # Verify an address
│   ├── statistics.rb             # Account statistics
│   └── sub_accounts.rb           # Sub-accounts (read-only by default)
├── sinatra_app/
│   └── app.rb                    # Sinatra web app
├── rails_app/                    # Rails API app
│   ├── app/controllers/
│   ├── config/
│   ├── Gemfile
│   └── README.md
├── Gemfile
├── .env.example
└── README.md

Resources

License

MIT