# Mailtrap Ruby Client ## Introduction The Mailtrap Ruby gem is the official client for integrating with the Mailtrap API v2, providing comprehensive email sending functionality for Ruby applications. This gem enables developers to send transactional and bulk emails through Mailtrap's infrastructure with full support for templating, attachments, custom headers, and batch operations. It seamlessly integrates with Ruby on Rails through ActionMailer while also providing a standalone API for pure Ruby applications. The gem offers three distinct sending modes: transactional email sending for real-time notifications, bulk sending for high-volume campaigns, and sandbox mode for development and testing. It includes complete API clients for managing email templates, contact lists, contact fields, suppressions, and contact imports. All operations are performed through a simple, well-documented interface with automatic error handling and proper HTTP response management. ## APIs and Key Functions ### Initialize Mailtrap Client Initialize a Mailtrap client to send emails through the API with support for transactional, bulk, or sandbox modes. ```ruby require 'mailtrap' # Basic initialization with API key from environment variable # Set MAILTRAP_API_KEY environment variable first client = Mailtrap::Client.new # Or provide API key directly client = Mailtrap::Client.new(api_key: 'your-api-key') # Initialize for bulk email sending bulk_client = Mailtrap::Client.new(api_key: 'your-api-key', bulk: true) # Initialize for sandbox testing sandbox_client = Mailtrap::Client.new( api_key: 'your-api-key', sandbox: true, inbox_id: 12 ) # Custom API host and port custom_client = Mailtrap::Client.new( api_key: 'your-api-key', api_host: 'alternative.host.mailtrap.io', api_port: 8080 ) ``` ### Send Email with Content Send a single email with custom content including subject, text, HTML body, and optional attachments. ```ruby require 'mailtrap' require 'base64' client = Mailtrap::Client.new(api_key: 'your-api-key') # Create mail object with full options mail = Mailtrap::Mail.from_content( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, to: [ { email: 'recipient@email.com', name: 'Recipient Name' } ], reply_to: { email: 'support@example.com', name: 'Support Team' }, cc: [ { email: 'cc@email.com', name: 'CC Recipient' } ], bcc: [ { email: 'bcc@email.com', name: 'BCC Recipient' } ], subject: 'You are awesome!', text: 'Congrats for sending test email with Mailtrap!', html: '

Congrats for sending test email with Mailtrap!

', category: 'Integration Test', attachments: [ { content: Base64.strict_encode64('Attachment content'), filename: 'attachment.txt' } ], headers: { 'X-Custom-Header': 'Custom header value' }, custom_variables: { year: 2025, user_id: 12345 } ) # Send the email response = client.send(mail) # => {:success=>true, :message_ids=>["abc123def456"]} # Or pass parameters directly without creating Mail object client.send( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, to: [{ email: 'recipient@email.com' }], subject: 'Quick Message', text: 'Hello from Mailtrap!' ) # Add attachments dynamically data = File.read('/path/to/image.jpg') encoded = Base64.encode64(data).gsub("\n", '') mail.add_attachment(content: encoded, filename: 'image.jpg') ``` ### Send Email with Template Send emails using pre-defined templates from the Mailtrap dashboard with variable substitution. ```ruby require 'mailtrap' client = Mailtrap::Client.new(api_key: 'your-api-key') # Create mail from template mail = Mailtrap::Mail.from_template( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, to: [ { email: 'user@email.com' } ], reply_to: { email: 'support@example.com', name: 'Support' }, template_uuid: '2f45b0aa-bbed-432f-95e4-e145e1965ba2', template_variables: { 'user_name' => 'John Doe', 'account_type' => 'Premium', 'expiry_date' => '2025-12-31' } ) # Send the templated email response = client.send(mail) # Or pass template parameters directly client.send( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, to: [{ email: 'user@email.com' }], template_uuid: '2f45b0aa-bbed-432f-95e4-e145e1965ba2', template_variables: { 'user_name' => 'Jane Doe' } ) ``` ### Batch Send Emails Send up to 500 emails in a single API call with shared base configuration and individual recipient customization. ```ruby require 'mailtrap' client = Mailtrap::Client.new(api_key: 'your-api-key') # Batch sending with custom content batch_base = Mailtrap::Mail.batch_base_from_content( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, subject: 'Weekly Newsletter', text: 'Thanks for subscribing!', html: '

Thanks for subscribing!

' ) # Add attachment to base (shared across all emails) File.open('newsletter.pdf') do |f| batch_base.add_attachment(content: f, filename: 'newsletter.pdf') end response = client.send_batch( batch_base, [ Mailtrap::Mail.from_content( to: [{ email: 'john.doe@email.com', name: 'John Doe' }] ), Mailtrap::Mail::Base.new( to: [{ email: 'jane.doe@email.com', name: 'Jane Doe' }] ), { to: [{ email: 'david.doe@email.com', name: 'David Doe' }] } ] ) # Batch sending with template batch_base = Mailtrap::Mail.batch_base_from_template( from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, reply_to: { email: 'support@example.com', name: 'Support' }, template_uuid: '339c8ab0-e73c-4269-984e-0d2446aacf2c' ) client.send_batch( batch_base, [ Mailtrap::Mail.from_template( to: [{ email: 'john.doe@email.com', name: 'John Doe' }], template_variables: { user_name: 'John Doe' } ), { to: [{ email: 'jane.doe@email.com', name: 'Jane Doe' }], template_variables: { user_name: 'Jane Doe' } } ] ) # Direct hash-based batch sending client.send_batch( { from: { email: 'mailtrap@example.com', name: 'Mailtrap Test' }, template_uuid: '339c8ab0-e73c-4269-984e-0d2446aacf2c' }, [ { to: [{ email: 'user1@email.com' }], template_variables: { user_name: 'User 1' } }, { to: [{ email: 'user2@email.com' }], template_variables: { user_name: 'User 2' } } ] ) ``` ### Manage Email Templates Create, retrieve, update, and delete email templates programmatically through the Email Templates API. ```ruby require 'mailtrap' account_id = 3229 client = Mailtrap::Client.new(api_key: 'your-api-key') templates = Mailtrap::EmailTemplatesAPI.new(account_id, client) # Create a new email template email_template = templates.create( name: 'Welcome Email', subject: 'Welcome to Mailtrap!', body_html: '

Welcome {{user_name}}!

Thanks for joining.

', body_text: 'Welcome {{user_name}}! Thanks for joining.', category: 'onboarding' ) # => # # List all email templates all_templates = templates.list # => [#, ...] # Get a specific email template template = templates.get(email_template.id) # Update an email template updated_template = templates.update( email_template.id, name: 'Welcome Email V2', subject: 'Welcome to Our Platform!', body_html: '

Welcome {{user_name}}!

Updated content.

' ) # Delete an email template templates.delete(email_template.id) # => nil ``` ### Manage Contacts and Contact Lists Create and manage contacts, contact lists, custom fields, and perform bulk contact imports. ```ruby require 'mailtrap' account_id = 3229 client = Mailtrap::Client.new(api_key: 'your-api-key') contact_lists = Mailtrap::ContactListsAPI.new(account_id, client) contacts = Mailtrap::ContactsAPI.new(account_id, client) contact_fields = Mailtrap::ContactFieldsAPI.new(account_id, client) # Create new contact list list = contact_lists.create(name: 'Newsletter Subscribers') # => # # List all contact lists all_lists = contact_lists.list # Update contact list updated_list = contact_lists.update(list.id, name: 'Premium Subscribers') # Create custom contact field field = contact_fields.create( name: 'Nickname', data_type: 'text', merge_tag: 'nickname' ) # => # # Create new contact with custom fields contact = contacts.create( email: 'john.doe@example.com', fields: { 'nickname' => 'Johnny' }, list_ids: [list.id] ) # => #"Johnny"}, # list_ids=[1], # status="subscribed", # created_at=1721212345, # updated_at=1721212345> contact.newly_created? # => true # Get contact by ID or email contact = contacts.get(contact.id) contact = contacts.get('john.doe@example.com') # Update or create contact (upsert) updated_contact = contacts.upsert( contact.id, email: 'john.updated@example.com', fields: { 'nickname' => 'John' } ) updated_contact.newly_created? # => false # Add contact to lists contacts.add_to_lists(contact.id, [list.id]) # Remove contact from lists contacts.remove_from_lists(contact.id, [list.id]) # Delete contact contacts.delete(contact.id) # Delete contact list contact_lists.delete(list.id) ``` ### Bulk Contact Import Import large numbers of contacts efficiently using the contact imports API with support for upserting, adding to lists, and removing from lists. ```ruby require 'mailtrap' account_id = 3229 client = Mailtrap::Client.new(api_key: 'your-api-key') contact_imports = Mailtrap::ContactImportsAPI.new(account_id, client) # Create bulk import using ContactsImportRequest builder import_request = Mailtrap::ContactsImportRequest.new.tap do |req| req.upsert(email: 'john.doe@example.com', fields: { first_name: 'John' }) .add_to_lists(email: 'john.doe@example.com', list_ids: [1]) .remove_from_lists(email: 'john.doe@example.com', list_ids: [2]) req.upsert(email: 'jane.smith@example.com', fields: { first_name: 'Jane' }) .add_to_lists(email: 'jane.smith@example.com', list_ids: [1]) .remove_from_lists(email: 'jane.smith@example.com', list_ids: [2]) end # Execute the import contact_import = contact_imports.create(import_request) # => # # Check import status import_status = contact_imports.get(contact_import.id) # => # # Alternative: Import using plain hash array contact_imports.create([ { email: 'john@example.com', fields: { first_name: 'John' }, list_ids_included: [1], list_ids_excluded: [2] }, { email: 'jane@example.com', fields: { first_name: 'Jane' }, list_ids_included: [1], list_ids_excluded: [2] } ]) ``` ### Manage Suppressions List and delete email suppressions (unsubscribes, bounces, spam complaints) for your account. ```ruby require 'mailtrap' account_id = 3229 client = Mailtrap::Client.new(api_key: 'your-api-key') suppressions = Mailtrap::SuppressionsAPI.new(account_id, client) # List all suppressions all_suppressions = suppressions.list # => [ # #, # ... # ] # Filter suppressions by email address user_suppressions = suppressions.list(email: 'recipient@example.com') # Delete a suppression to allow sending to that address again suppressions.delete(user_suppressions.first.id) # => nil ``` ### Rails ActionMailer Integration Configure ActionMailer to use Mailtrap as the delivery method in Ruby on Rails applications. ```ruby # config/environments/production.rb config.action_mailer.delivery_method = :mailtrap # Set MAILTRAP_API_KEY environment variable, or customize settings: config.action_mailer.mailtrap_settings = { api_key: Rails.application.credentials.mailtrap_api_key, bulk: false # Set to true for bulk sending stream } # For sandbox testing in development # config/environments/development.rb config.action_mailer.delivery_method = :mailtrap config.action_mailer.mailtrap_settings = { api_key: ENV['MAILTRAP_API_KEY'], sandbox: true, inbox_id: 12 } # app/mailers/user_mailer.rb class UserMailer < ApplicationMailer def welcome_email(user) mail( to: user.email, reply_to: 'support@example.com', subject: 'Welcome to Our Platform!', category: 'onboarding', custom_variables: { user_id: user.id, signup_date: user.created_at } ) end end # Send email UserMailer.welcome_email(@user).deliver_now ``` ### Multiple Mailtrap Clients in Rails Configure multiple Mailtrap delivery methods to use both transactional and bulk APIs simultaneously. ```ruby # config/application.rb ActionMailer::Base.add_delivery_method( :mailtrap_bulk, Mailtrap::ActionMailer::DeliveryMethod ) # config/environments/production.rb config.action_mailer.delivery_method = :mailtrap config.action_mailer.mailtrap_settings = { api_key: ENV['MAILTRAP_API_KEY'] } config.action_mailer.mailtrap_bulk_settings = { api_key: ENV['MAILTRAP_API_KEY'], bulk: true } # app/mailers/newsletter_mailer.rb class NewsletterMailer < ApplicationMailer def weekly_digest(user) mail( to: user.email, subject: 'Your Weekly Digest', delivery_method: :mailtrap_bulk # Use bulk API ) end end # app/mailers/transactional_mailer.rb class TransactionalMailer < ApplicationMailer def password_reset(user) mail( to: user.email, subject: 'Password Reset Request' # Uses default :mailtrap delivery method (transactional API) ) end end ``` ## Summary The Mailtrap Ruby gem serves as a comprehensive solution for email delivery in Ruby applications, supporting both standalone Ruby projects and Ruby on Rails through ActionMailer integration. The primary use cases include transactional email delivery for user notifications and system alerts, bulk email campaigns for newsletters and marketing communications, template-based email sending with variable substitution, batch operations for efficient high-volume sending, and sandbox mode for safe development and testing without affecting real inboxes. The gem also provides complete contact management capabilities including list management, custom fields, bulk imports, and suppression handling for compliance with email best practices. Integration patterns vary based on application needs: Rails applications benefit from seamless ActionMailer integration by simply setting the delivery method and API credentials in environment configuration files, while pure Ruby applications use the client directly with explicit Mail object creation. The gem supports multiple deployment scenarios including single-tenant applications with one API key, multi-tenant systems requiring different sending streams per tenant, and hybrid setups using both transactional and bulk APIs simultaneously. All API operations include proper error handling with specific exception types for authorization failures, rate limits, payload size errors, and rejection scenarios, enabling robust production deployments with comprehensive monitoring and error recovery strategies.