Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,34 @@
## Unreleased

- Add Sending Stats API

## [2.8.0] - 2026-03-03

- Add Account Accesses API
- Add Billing API

## [2.7.0] - 2026-02-24
## [2.7.0] - 2026-02-24

- Add Sandbox Messages API
- Add Sending Domains API
- Add Sandbox Attachments API
- Add Accounts API

## [2.6.0] - 2026-01-27

- Add Inboxes API
- Add Projects API
- Models' `to_h` now returns all fields without compacting

## [2.5.0] - 2025-11-10

- Add Contact Imports API
- Add Suppressions API
- Write the message IDs to the message when sending with Action Mailer
- Fix versioning :)

## [2.4.1] - 2025-08-21

- Set `template_uuid` and `template_variables` when building mail from `Mail::Message`

## [2.4.0] - 2025-08-04
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ Email API:
- Full Email Sending – [`full.rb`](examples/full.rb)
- Batch Sending – [`batch.rb`](examples/batch.rb)
- Sending Domains API – [`sending_domains_api.rb`](examples/sending_domains_api.rb)
- Sending Stats API – [`stats_api.rb`](examples/stats_api.rb)

Email Sandbox (Testing):

Expand Down
48 changes: 48 additions & 0 deletions examples/stats_api.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
require 'mailtrap'
require 'date'
require 'time'

account_id = 3229
client = Mailtrap::Client.new(api_key: 'your-api-key')
stats = Mailtrap::StatsAPI.new(account_id, client)

# Get aggregated sending stats
stats.get(start_date: '2026-01-01', end_date: '2026-01-31')
Copy link
Contributor

@i7an i7an Mar 6, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i believe the start and end dates should be of type #to_date:

stats.get(start_date: Date.today - 10, end_date: Date.today)

In the code you can do date.to_date which should work for Date and Time. In RoR applications it should work with strings as well.

URI.encode_www_form({start_date: (Time.now - 10).to_date})
# => "start_date=2026-03-06"

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In our client we are already doing
uri.query = URI.encode_www_form(query_params) if query_params.any?

so you can safely use Date in any query param

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

require 'time'

account_id = 3229
client = Mailtrap::Client.new(api_key: 'your-api-key')
stats = Mailtrap::StatsAPI.new(account_id, client)

stats.get(start_date: Time.now, end_date: '2026-01-31')
# => https://mailtrap.io/api/accounts/3229/stats?start_date=2026-03-09+11%3A25%3A22+%2B0100&end_date=2026-01-31

# => #<struct Mailtrap::SendingStats
# delivery_count=150, delivery_rate=0.95,
# bounce_count=8, bounce_rate=0.05,
# open_count=120, open_rate=0.8,
# click_count=60, click_rate=0.5,
# spam_count=2, spam_rate=0.013>

# Get stats grouped by domain
stats.by_domain(start_date: '2026-01-01', end_date: '2026-01-31')
# => [#<struct Mailtrap::SendingStatGroup
# name=:sending_domain_id, value=1,
# stats=#<struct Mailtrap::SendingStats delivery_count=100, ...>>, ...]

# Get stats grouped by category
stats.by_category(start_date: Date.today.prev_day(30), end_date: Date.today)
# => [#<struct Mailtrap::SendingStatGroup
# name=:category, value="Transactional",
# stats=#<struct Mailtrap::SendingStats delivery_count=100, ...>>, ...]

# Get stats grouped by email service provider
stats.by_email_service_provider(start_date: Time.new(2026, 1, 1), end_date: Time.new(2026, 1, 31))
# => [#<struct Mailtrap::SendingStatGroup
# name=:email_service_provider, value="Gmail",
# stats=#<struct Mailtrap::SendingStats delivery_count=80, ...>>, ...]

# Get stats grouped by date
stats.by_date(start_date: '2026-01-01', end_date: '2026-01-31')
# => [#<struct Mailtrap::SendingStatGroup
# name=:date, value="2026-01-01",
# stats=#<struct Mailtrap::SendingStats delivery_count=5, ...>>, ...]

# With optional filters
stats.get(
start_date: '2026-01-01',
end_date: '2026-01-31',
sending_domain_ids: [1, 2],
categories: ['Transactional']
)
1 change: 1 addition & 0 deletions lib/mailtrap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
require_relative 'mailtrap/inboxes_api'
require_relative 'mailtrap/sandbox_messages_api'
require_relative 'mailtrap/sandbox_attachments_api'
require_relative 'mailtrap/stats_api'
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sending_stats and sending_stat_group are required in stats_api. thus no need to require them explicitly


module Mailtrap
# @!macro api_errors
Expand Down
15 changes: 15 additions & 0 deletions lib/mailtrap/sending_stat_group.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

module Mailtrap
# Data Transfer Object for grouped Sending Stats data
# @attr_reader name [Symbol] Group type (:category, :date, :sending_domain_id, :email_service_provider)
# @attr_reader value [String, Integer] Group value (e.g., "Transactional", "2026-01-01", 1, "Gmail")
# @attr_reader stats [SendingStats] Sending stats for this group
#
SendingStatGroup = Struct.new(
:name,
:value,
:stats,
keyword_init: true
)
end
30 changes: 30 additions & 0 deletions lib/mailtrap/sending_stats.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# frozen_string_literal: true

module Mailtrap
# Data Transfer Object for Sending Stats data
# @see https://docs.mailtrap.io/developers/email-sending-stats
# @attr_reader delivery_count [Integer] Number of delivered emails
# @attr_reader delivery_rate [Float] Delivery rate
# @attr_reader bounce_count [Integer] Number of bounced emails
# @attr_reader bounce_rate [Float] Bounce rate
# @attr_reader open_count [Integer] Number of opened emails
# @attr_reader open_rate [Float] Open rate
# @attr_reader click_count [Integer] Number of clicked emails
# @attr_reader click_rate [Float] Click rate
# @attr_reader spam_count [Integer] Number of spam reports
# @attr_reader spam_rate [Float] Spam rate
#
SendingStats = Struct.new(
:delivery_count,
:delivery_rate,
:bounce_count,
:bounce_rate,
:open_count,
:open_rate,
:click_count,
:click_rate,
:spam_count,
:spam_rate,
keyword_init: true
)
end
151 changes: 151 additions & 0 deletions lib/mailtrap/stats_api.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
# frozen_string_literal: true

require 'date'
require_relative 'base_api'
require_relative 'sending_stats'
require_relative 'sending_stat_group'

module Mailtrap
class StatsAPI
include BaseAPI

ARRAY_FILTERS = %i[sending_domain_ids sending_streams categories email_service_providers].freeze
GROUP_KEYS = {
'domains' => :sending_domain_id,
'categories' => :category,
'email_service_providers' => :email_service_provider,
'date' => :date
}.freeze

# Get aggregated sending stats
# @param start_date [String, Date, Time] Start date for the stats period (required)
# @param end_date [String, Date, Time] End date for the stats period (required)
# @param sending_domain_ids [Array<Integer>] Filter by sending domain IDs
# @param sending_streams [Array<String>] Filter by sending streams
# @param categories [Array<String>] Filter by categories
# @param email_service_providers [Array<String>] Filter by email service providers
# @return [SendingStats] Aggregated sending stats
# @!macro api_errors
def get(start_date:, end_date:, sending_domain_ids: nil, sending_streams: nil, categories: nil, # rubocop:disable Metrics/ParameterLists
email_service_providers: nil)
query_params = build_query_params(
start_date, end_date,
{ sending_domain_ids:, sending_streams:, categories:, email_service_providers: }
)
response = client.get(base_path, query_params)
build_entity(response, SendingStats)
end

# Get sending stats grouped by domain
# @param start_date [String, Date, Time] Start date for the stats period (required)
# @param end_date [String, Date, Time] End date for the stats period (required)
# @param sending_domain_ids [Array<Integer>] Filter by sending domain IDs
# @param sending_streams [Array<String>] Filter by sending streams
# @param categories [Array<String>] Filter by categories
# @param email_service_providers [Array<String>] Filter by email service providers
# @return [Array<SendingStatGroup>] Array of SendingStatGroup structs with sending_domain_id and stats
# @!macro api_errors
def by_domain(start_date:, end_date:, sending_domain_ids: nil, sending_streams: nil, categories: nil, # rubocop:disable Metrics/ParameterLists
email_service_providers: nil)
grouped_stats('domains', start_date, end_date,
{ sending_domain_ids:, sending_streams:, categories:, email_service_providers: })
end

# Get sending stats grouped by category
# @param start_date [String, Date, Time] Start date for the stats period (required)
# @param end_date [String, Date, Time] End date for the stats period (required)
# @param sending_domain_ids [Array<Integer>] Filter by sending domain IDs
# @param sending_streams [Array<String>] Filter by sending streams
# @param categories [Array<String>] Filter by categories
# @param email_service_providers [Array<String>] Filter by email service providers
# @return [Array<SendingStatGroup>] Array of SendingStatGroup structs with category and stats
# @!macro api_errors
def by_category(start_date:, end_date:, sending_domain_ids: nil, sending_streams: nil, categories: nil, # rubocop:disable Metrics/ParameterLists
email_service_providers: nil)
grouped_stats('categories', start_date, end_date,
{ sending_domain_ids:, sending_streams:, categories:, email_service_providers: })
end

# Get sending stats grouped by email service provider
# @param start_date [String, Date, Time] Start date for the stats period (required)
# @param end_date [String, Date, Time] End date for the stats period (required)
# @param sending_domain_ids [Array<Integer>] Filter by sending domain IDs
# @param sending_streams [Array<String>] Filter by sending streams
# @param categories [Array<String>] Filter by categories
# @param email_service_providers [Array<String>] Filter by email service providers
# @return [Array<SendingStatGroup>] Array of SendingStatGroup structs with email_service_provider and stats
# @!macro api_errors
def by_email_service_provider(start_date:, end_date:, sending_domain_ids: nil, sending_streams: nil, # rubocop:disable Metrics/ParameterLists
categories: nil, email_service_providers: nil)
grouped_stats('email_service_providers', start_date, end_date,
{ sending_domain_ids:, sending_streams:, categories:, email_service_providers: })
end

# Get sending stats grouped by date
# @param start_date [String, Date, Time] Start date for the stats period (required)
# @param end_date [String, Date, Time] End date for the stats period (required)
# @param sending_domain_ids [Array<Integer>] Filter by sending domain IDs
# @param sending_streams [Array<String>] Filter by sending streams
# @param categories [Array<String>] Filter by categories
# @param email_service_providers [Array<String>] Filter by email service providers
# @return [Array<SendingStatGroup>] Array of SendingStatGroup structs with date and stats
# @!macro api_errors
def by_date(start_date:, end_date:, sending_domain_ids: nil, sending_streams: nil, categories: nil, # rubocop:disable Metrics/ParameterLists
email_service_providers: nil)
grouped_stats('date', start_date, end_date,
{ sending_domain_ids:, sending_streams:, categories:, email_service_providers: })
end

private

def grouped_stats(group, start_date, end_date, filters)
query_params = build_query_params(start_date, end_date, filters)
response = client.get("#{base_path}/#{group}", query_params)
group_key = GROUP_KEYS.fetch(group)

response.map do |item|
SendingStatGroup.new(
name: group_key,
value: item[group_key],
stats: build_entity(item[:stats], SendingStats)
)
end
end

def build_query_params(start_date, end_date, filters)
params = { start_date: normalize_date(start_date), end_date: normalize_date(end_date) }

ARRAY_FILTERS.each do |filter_key|
values = filters[filter_key]
params["#{filter_key}[]"] = values if values
end

params
end

def normalize_date(value)
case value
when Date
value.iso8601
when Time
value.strftime('%F')
when String
unless /\A\d{4}-\d{2}-\d{2}\z/.match?(value)
raise ArgumentError,
"Invalid date: #{value.inspect}. Expected a Date, Time, or String in YYYY-MM-DD format."
end

Date.iso8601(value).iso8601
else
raise ArgumentError,
"Invalid date: #{value.inspect}. Expected a Date, Time, or String in YYYY-MM-DD format."
end
rescue Date::Error
raise ArgumentError, "Invalid date: #{value.inspect}. Expected a Date, Time, or String in YYYY-MM-DD format."
end

def base_path
"/api/accounts/#{account_id}/stats"
end
end
end

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading