This directory contains Ruby implementations of Mandrill API use cases using the mailchimp-transactional gem.
- Ruby 2.7 or higher (Ruby 3.0+ recommended)
- Bundler gem manager
- A Mandrill API key from Mailchimp
- Install Bundler if you haven't already:
gem install bundler- Install the required gems:
cd scripts
bundle installInstall the required gems individually:
gem install MailchimpTransactional dotenv- Copy the
.env.examplefile to.envin the scripts directory:
cp env.example .env- Edit the
.envfile and add your credentials:
MANDRILL_API_KEY=your_mandrill_api_key_here
DEFAULT_FROM_EMAIL=sender@yourdomain.com
DEFAULT_FROM_NAME="Your Name"
DEFAULT_TO_EMAIL=recipient@example.com
DEFAULT_TO_NAME="Recipient Name"Note: Always quote values that contain spaces or special characters.
File: email_with_single_recipient.rb
Demonstrates how to send a basic email to a single recipient.
ruby email_with_single_recipient.rb
# Or with Bundler:
bundle exec ruby email_with_single_recipient.rb
# Or make executable:
./email_with_single_recipient.rbFeatures:
- Basic email sending
- HTML and plain text content
- Custom headers
- Advanced options with tracking and metadata
- Comprehensive error handling
File: email_with_merge_tags.rb
Personalize emails using merge tags for dynamic content.
ruby email_with_merge_tags.rbFeatures:
- Global merge variables (apply to all recipients)
- Recipient-specific merge variables
- Handlebars template syntax
- Multiple recipient personalization
- Full RDoc documentation
File: email_with_template.rb
Send emails using pre-created Mandrill templates.
ruby email_with_template.rbFeatures:
- Use stored templates
- Override template defaults
- Dynamic content with merge tags
- mc:edit region replacement
- Batch sending with templates
Note: You must first create a template using create_template.rb or via the Mandrill UI.
File: email_with_attachments.rb
Attach files (PDF, CSV, JSON, etc.) to your emails.
ruby email_with_attachments.rbFeatures:
- Attach local files (PDF, images, etc.)
- Create dynamic attachments (CSV, JSON, text)
- Base64 encoding handling
- Multiple attachment types
- MIME type helpers
File: create_template.rb
Create and manage reusable email templates.
ruby create_template.rbFeatures:
- Create new templates
- List all templates
- Get template information
- Update and delete templates
- mc:edit regions for dynamic content
- Advanced template with responsive design
File: kitchen_sink_email.rb
Comprehensive example demonstrating all Mandrill features.
ruby kitchen_sink_email.rbFeatures:
- All message options in one example
- Attachments, tracking, metadata
- Multiple recipient types (TO, CC, BCC)
- Scheduled sending
- Advanced headers and custom fields
- Complete documentation with RDoc
File: sms_single_recipient.rb
Send SMS messages using the Mandrill API.
ruby sms_single_recipient.rbFeatures:
- Send SMS to a single recipient
- Phone numbers in E.164 format
- Consent type configuration (onetime, recurring)
- Click tracking for URLs
- Uses REST API directly (API v1.1)
Note: SMS functionality requires:
- A verified sender phone number in your Mandrill account
- SMS enabled for your account
- Proper recipient consent
Each Ruby script follows this structure:
- Shebang and encoding - Ruby interpreter declaration
- Documentation block - Usage and requirements
- Require statements - Required gems and libraries
- Client initialization - Configure Mandrill API client
- Method definitions - Reusable email sending methods
- Main execution block - Run the example when script is executed directly
All scripts include error handling for:
- Missing API credentials
- API client errors (
MailchimpTransactional::ApiError) - Network issues
- Invalid email addresses
Example error handling pattern:
begin
result = mailchimp.messages.send(message: message)
# Handle success
rescue MailchimpTransactional::ApiError => e
puts "Mandrill API Error: #{e.message}"
puts "Error details: #{e.response_body}" if e.respond_to?(:response_body)
endA successful API response is an array of hashes:
[
{
"email" => "recipient@example.org",
"status" => "sent", # or "queued", "rejected", "invalid"
"_id" => "abc123",
"reject_reason" => nil # or reason if rejected
}
]sent- Message was successfully sentqueued- Message is queued for sendingscheduled- Message is scheduled for future sendingrejected- Message was rejectedinvalid- Invalid recipient email address
Ruby allows both symbols and strings as hash keys. The Mandrill API accepts both:
# Using symbols (Ruby convention)
message = {
subject: 'Hello',
from_email: 'test@example.org'
}
# Using strings (also works)
message = {
'subject' => 'Hello',
'from_email' => 'test@example.org'
}Ruby uses snake_case for method names:
mailchimp.messages.send() # Send message
mailchimp.messages.send_template() # Send with template
mailchimp.templates.add() # Create templateRuby uses true and false (lowercase):
message = {
track_opens: true,
track_clicks: false
}Make the script executable:
chmod +x email_with_single_recipient.rb
./email_with_single_recipient.rbruby email_with_single_recipient.rbEnsures correct gem versions are used:
bundle exec ruby email_with_single_recipient.rbTo test without sending real emails, you can:
- Use print statements to inspect the message structure:
puts "Message structure:"
puts JSON.pretty_generate(message)- Create a dry-run mode:
DRY_RUN = ENV['DRY_RUN'] == 'true'
if DRY_RUN
puts "DRY RUN - Would send:"
puts JSON.pretty_generate(message)
else
result = mailchimp.messages.send(message: message)
endA Gemfile is included in the scripts directory:
source 'https://rubygems.org'
gem 'MailchimpTransactional', '~> 1.0'
gem 'dotenv', '~> 2.8'bundle installbundle updatebundle listscripts/
├── Gemfile # Ruby dependencies
├── Gemfile.lock # Locked gem versions (created by bundler)
├── .env # Environment variables (create from env.example)
├── env.example # Example environment variables
├── email_with_single_recipient.rb # Send single email
├── email_with_merge_tags.rb # Send email with merge tags
├── email_with_template.rb # Send email using template
├── email_with_attachments.rb # Send email with attachments
├── create_template.rb # Create Mandrill templates
├── kitchen_sink_email.rb # All features combined
├── sms_single_recipient.rb # Send SMS message
└── README_USECASES_RUBY.md # This file
LoadError: cannot load such file -- MailchimpTransactional
Solution:
gem install MailchimpTransactional
# or
bundle installPermission denied @ rb_sysopen - .env
Solution:
Check file permissions and ensure .env exists:
ls -la .env
chmod 644 .envYour Ruby version is X.X.X, but your Gemfile specified >= Y.Y.Y
Solution: Install a compatible Ruby version using rbenv or rvm:
# Using rbenv
rbenv install 3.2.0
rbenv local 3.2.0
# Using rvm
rvm install 3.2.0
rvm use 3.2.0For issues with:
- Mandrill API: Contact Mailchimp support
- Ruby SDK: Open an issue on the GitHub repository
- These examples: Check the use-cases documentation
See the LICENSE file in the root directory.