Skip to content
Draft
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ Email marketing:

- Email Campaigns CRUD, Lifecycle Actions & Stats – [`email_campaigns_api.rb`](examples/email_campaigns_api.rb)
- Email Marketing Stats API – [`marketing_stats_api.rb`](examples/marketing_stats_api.rb)
- Subscription Topics API – [`subscription_topics_api.rb`](examples/subscription_topics_api.rb)

General:

Expand Down
37 changes: 37 additions & 0 deletions examples/contacts_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,26 @@
# updated_at=1721212355>
updated_contact.newly_created? # => false

# Set the contact's subscription topic preferences, one per topic and sending domain
# (see subscription_topics_api.rb); preferences left out keep their status.
# A topic with a domain_id applies to that domain only; one without applies to every domain.
# Without subscription topics, listing them raises Mailtrap::RejectionError, Contact#subscription_topics
# is nil and setting them raises Mailtrap::Error ("are not available for this account").
begin
topic = Mailtrap::SubscriptionTopicsAPI.new(client).list(per_page: 1).data.first
topic_domain_id = topic && (topic.domain_id || Mailtrap::DomainsAPI.new(account_id, client).list.first&.id)
if topic_domain_id
topic_contact = contacts.upsert(
contact.id,
subscription_topics: [{ subscription_topic_id: topic.id, domain_id: topic_domain_id, status: 'unsubscribed' }]
)
topic_contact.subscription_topics
# => [{ subscription_topic_id: 12, domain_id: 4321, status: "unsubscribed" }, ...]
end
rescue Mailtrap::Error => e
puts "Subscription topic preferences are not available: #{e.message}"
end

# Remove contact from lists
contacts.remove_from_lists(contact.id, [list.id])
# => #<struct Mailtrap::Contact
Expand Down Expand Up @@ -180,3 +200,20 @@
{ email: 'jane@example.com', fields: { first_name: 'Jane' }, list_ids_included: [1], list_ids_excluded: [2] }
]
)

# Import subscription topic preferences, as for contacts.upsert above
# (on an account without subscription topics, the import fails)
if topic_domain_id
topics_import = Mailtrap::ContactsImportRequest.new.tap do |req|
req.upsert(email: 'john.doe@example.com')
.update_subscription_topics(
email: 'john.doe@example.com',
subscription_topics: [{ subscription_topic_id: topic.id, domain_id: topic_domain_id, status: 'subscribed' }]
)
end
begin
contact_imports.create(topics_import)
rescue Mailtrap::Error => e
puts "Subscription topic preferences are not available: #{e.message}"
end
end
12 changes: 12 additions & 0 deletions examples/email_campaigns_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,18 @@
)
# => #<struct Mailtrap::EmailCampaign id=4567, name="Spring Sale (updated)", ...>

# Set the campaign's subscription topic: one with no domain_id covers every domain, otherwise it
# must be the campaign's domain (see subscription_topics_api.rb). A topic can be changed, not removed.
begin
topic = Mailtrap::SubscriptionTopicsAPI.new(client).list.data.find do |t|
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
t.domain_id.nil? || t.domain_id == email_campaign.domain_id
end
email_campaigns.update(email_campaign.id, subscription_topic_id: topic.id) if topic
# => #<struct Mailtrap::EmailCampaign id=4567, subscription_topic_id=12, ...>
rescue Mailtrap::RejectionError
puts 'Subscription topics are not available for this account'
end

# Schedule the draft Email Campaign to start sending at a future time
schedule_at = (Time.now.utc + 86_400).strftime('%Y-%m-%dT%H:%M:%S.000Z')
email_campaigns.schedule(email_campaign.id, schedule_at)
Expand Down
13 changes: 12 additions & 1 deletion examples/email_logs_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,16 @@
# events=[#<struct Mailtrap::EmailLogEvent event_type="delivery", ...>, ...]>

puts message.raw_message_url
message.events&.each { |e| puts "#{e.event_type} at #{e.created_at}" }

# A recipient changing their subscription topic preferences adds topic_unsubscribe and
# topic_resubscribe events. An event type this version doesn't know keeps its details as a Hash.
message.events&.each do |e|
puts "#{e.event_type} at #{e.created_at}"
case e.details
when Mailtrap::EmailLogEventDetails::TopicSubscription
puts "#{e.event_type}: subscription topic #{e.details.subscription_topic_id}"
when Hash
puts "#{e.event_type}: #{e.details}"
end
end
end
35 changes: 35 additions & 0 deletions examples/subscription_topics_api.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
require 'mailtrap'

client = Mailtrap::Client.new(api_key: 'your-api-key')
subscription_topics = Mailtrap::SubscriptionTopicsAPI.new(client)

# Subscription topics are created in the Mailtrap app; the API reads them, so that campaigns
# (subscription_topic_id) and contacts (subscription_topics) can refer to their IDs.
begin
# Get the subscription topics (paginated, by ID; deleted topics are left out)
list = subscription_topics.list(per_page: 50)
# => #<struct Mailtrap::SubscriptionTopicsListResponse
# data=[#<struct Mailtrap::SubscriptionTopic ...>],
# pagination={:token=>1, :prev_token=>nil, :next_token=>2, ...}>
list.data
# => [#<struct Mailtrap::SubscriptionTopic
# id=12,
# name="Product updates",
# description="News about our product",
# domain_id=nil,
# deleted_at=nil,
# created_at="2026-11-01T10:00:00Z",
# updated_at="2026-11-02T10:00:00Z">]
# domain_id is nil for a topic that covers every sending domain

# Get the next page
next_token = list.pagination[:next_token]
subscription_topics.list(per_page: 50, token: next_token) if next_token

# Get a single subscription topic; a deleted one is returned too, with deleted_at set
topic = list.data.first
subscription_topics.get(topic.id) if topic
# => #<struct Mailtrap::SubscriptionTopic id=12, name="Product updates", ...>
rescue Mailtrap::RejectionError
puts 'Subscription topics are not available for this account'
end
7 changes: 7 additions & 0 deletions examples/suppressions_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@
# Get suppressions for the email
suppressions.list(email: 'recipient@example.com')

# Include the contacts' subscription topic unsubscriptions. They can't be created or deleted
# here: change them with the contact's subscription_topics (see contacts_api.rb).
suppressions.list(include_topic_unsubscriptions: true)
# => [..., #<struct Mailtrap::Suppression
# id="0b7e4f1a-...", type="topic unsubscription", email="recipient@example.com",
# sending_stream="bulk", domain_name="example.com", subscription_topic_id=12, ...>]

# Add an email to the suppression list.
# `type` is optional and defaults to 'manual import'.
suppression = suppressions.create(
Expand Down
13 changes: 13 additions & 0 deletions examples/webhooks_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,19 @@
)
# => #<struct Mailtrap::Webhook id=1, url="https://example.com/mailtrap/webhooks", ..., signing_secret="a1b2c3...">

# Event types: delivery, soft_bounce, bounce, suspension, unsubscribe, open, spam_complaint, click,
# reject and subscription_preferences_update. The last one, sent when a recipient changes their
# subscription topic preferences, is available only on `campaigns` webhooks and on `email_sending`
# webhooks of the `bulk` stream.

# Create a `campaigns` webhook
webhooks_api.create(
url: 'https://example.com/mailtrap/campaigns',
webhook_type: 'campaigns',
payload_format: 'json',
event_types: %w[unsubscribe subscription_preferences_update]
)

# Create an `audit_log` webhook
webhooks_api.create(
url: 'https://example.com/mailtrap/audit-log',
Expand Down
1 change: 1 addition & 0 deletions lib/mailtrap.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
require_relative 'mailtrap/suppressions_api'
require_relative 'mailtrap/tracking_opt_outs_api'
require_relative 'mailtrap/email_campaigns_api'
require_relative 'mailtrap/subscription_topics_api'
require_relative 'mailtrap/marketing_stats_api'
require_relative 'mailtrap/domains_api'
require_relative 'mailtrap/sending_domains_api'
Expand Down
13 changes: 11 additions & 2 deletions lib/mailtrap/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -318,15 +318,15 @@ def handle_response(response) # rubocop:disable Metrics/CyclomaticComplexity, Me
when Net::HTTPUnauthorized
raise Mailtrap::AuthorizationError, response_errors(response)
when Net::HTTPForbidden
raise Mailtrap::RejectionError, response_errors(response)
raise Mailtrap::RejectionError, response.body.to_s.empty? ? ['forbidden'] : response_errors(response)
when Net::HTTPPayloadTooLarge
raise Mailtrap::MailSizeError, ['message too large']
when Net::HTTPTooManyRequests
raise Mailtrap::RateLimitError, ['too many requests']
when Net::HTTPClientError
raise Mailtrap::Error, ["client error '#{response.body}'"]
when Net::HTTPServerError
raise Mailtrap::Error, ['server error']
raise Mailtrap::Error, server_errors(response)
else
raise Mailtrap::Error, ["unexpected status code=#{response.code}"]
end
Expand All @@ -349,6 +349,15 @@ def response_errors(response)
end
end

# The body's errors when it has them, such as the contacts 503 that names the contact to update
def server_errors(response)
body = json_response(response.body) if json_response?(response)
errors = body.is_a?(Hash) ? Array(body[:errors] || body[:error]).compact : []
errors.empty? ? ['server error'] : errors
rescue JSON::ParserError
['server error']
Comment on lines +357 to +358

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[could] Nothing tests this fallback: you can delete the rescue and the client spec still passes. Without it, a 5xx with an empty body sent as application/json raises JSON::ParserError instead of Mailtrap::Error, so one more case next to the HTML one, with body: '' and the JSON header, would keep it covered.

end

def json_response?(response)
response.content_type == 'application/json'
end
Expand Down
5 changes: 5 additions & 0 deletions lib/mailtrap/contact.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ module Mailtrap
# @attr_reader status [String] The contact status (subscribed/unsubscribed)
# @attr_reader created_at [Integer] The creation timestamp
# @attr_reader updated_at [Integer] The last update timestamp
# @attr_reader subscription_topics [Array<Hash>, nil] The contact's subscription topic preferences,
# each +{ subscription_topic_id:, domain_id:, status: }+ with +status+ +subscribed+ or +unsubscribed+;
# empty when the account has no live topics. +nil+ when subscription topics are not available for the account,
# or when the preferences could not be read (retry then)
Contact = Struct.new(
:id,
:email,
Expand All @@ -18,6 +22,7 @@ module Mailtrap
:status,
:created_at,
:updated_at,
:subscription_topics,
keyword_init: true
) do
def initialize(options)
Expand Down
6 changes: 5 additions & 1 deletion lib/mailtrap/contact_imports_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Mailtrap
class ContactImportsAPI
include BaseAPI

self.supported_options = %i[email fields list_ids_included list_ids_excluded]
self.supported_options = %i[email fields list_ids_included list_ids_excluded subscription_topics]

self.response_class = ContactImport

Expand All @@ -29,6 +29,10 @@ def get(import_id)
# req.upsert(email: 'john@example.com', fields: { first_name: 'John' })
# .add_to_lists(email: 'john@example.com', list_ids: [1])
# .remove_from_lists(email: 'john@example.com', list_ids: [2])
# .update_subscription_topics(
# email: 'john@example.com',
# subscription_topics: [{ subscription_topic_id: 3, domain_id: 4, status: 'unsubscribed' }]
# )
# end
# contact_imports.create(import_request)
#
Expand Down
14 changes: 12 additions & 2 deletions lib/mailtrap/contacts_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ module Mailtrap
class ContactsAPI
include BaseAPI

self.supported_options = %i[email fields list_ids]
self.supported_options = %i[email fields list_ids subscription_topics]
self.response_class = Contact

# Retrieves a specific contact
Expand All @@ -23,9 +23,13 @@ def get(contact_id)
# @option options [String] :email The contact's email address
# @option options [Hash] :fields The contact's fields
# @option options [Array<Integer>] :list_ids The contact's list IDs
# @option options [Array<Hash>] :subscription_topics Subscription topic preferences,
# see {#upsert}
# @return [Contact] Created contact object
# @!macro api_errors
# @raise [ArgumentError] If invalid options are provided
# @raise [Mailtrap::Error] With a 503 when the contact was saved but its subscription topic
# preferences were not; send them again with {#upsert}
def create(options)
base_create(options)
end
Expand All @@ -44,11 +48,17 @@ def delete(contact_id)
# @option options [String] :email The contact's email address
# @option options [Hash] :fields The contact's fields
# @option options [Boolean] :unsubscribed Whether to unsubscribe the contact
# @option options [Array<Hash>] :subscription_topics Subscription topic preferences to set, each
# +{ subscription_topic_id:, domain_id:, status: }+ with +status+ +subscribed+ or +unsubscribed+
# and +domain_id+ the sending domain it applies to; preferences left out keep their status.
# Fails with a validation error on an account without subscription topics
# @return [Contact] Updated contact object
# @!macro api_errors
# @raise [ArgumentError] If invalid options are provided
# @raise [Mailtrap::Error] With a 503 when the contact was saved but its subscription topic
# preferences were not; send them again in an update of the contact
def upsert(contact_id, options)
base_update(contact_id, options, %i[email fields unsubscribed])
base_update(contact_id, options, %i[email fields unsubscribed subscription_topics])
end

# Adds a contact to specified lists
Expand Down
28 changes: 28 additions & 0 deletions lib/mailtrap/contacts_import_request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ def remove_from_lists(email:, list_ids:)
self
end

# Sets the contact's subscription topic preferences; preferences left out keep their status, and
# a later preference for the same topic and domain replaces the earlier one.
# Importing them fails on an account without subscription topics.
# @param email [String] The contact's email address
# @param subscription_topics [Array<Hash>] Preferences, each +{ subscription_topic_id:, domain_id:, status: }+
# with +status+ +subscribed+ or +unsubscribed+ and +domain_id+ the sending domain it applies to
# @return [ContactsImportRequest] Returns self for method chaining
def update_subscription_topics(email:, subscription_topics:)
validate_email!(email)
raise ArgumentError, 'subscription_topics must be present' if subscription_topics.empty?

merge_subscription_topics(email:, subscription_topics:)

self
end

# @return [Array<Hash>] Array of contact objects ready for import
def to_a
@data.values
Expand All @@ -63,5 +79,17 @@ def append_list_ids(email:, list_ids:, key:)

@data[email][key] |= list_ids
end

# The API rejects an import that repeats a topic and domain for a contact
def merge_subscription_topics(email:, subscription_topics:)
preferences = Array(@data[email][:subscription_topics]).to_h do |preference|
[preference.values_at(:subscription_topic_id, :domain_id), preference]
end
subscription_topics.each do |preference|
preference = preference.transform_keys(&:to_sym)
preferences[preference.values_at(:subscription_topic_id, :domain_id)] = preference
end
@data[email][:subscription_topics] = preferences.values
end
end
end
3 changes: 3 additions & 0 deletions lib/mailtrap/email_campaign.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ module Mailtrap
# @attr_reader contact_segment_ids [Array<Integer>] IDs of the contact segments included in the campaign's audience
# @attr_reader delivery_mode [String] How the campaign is delivered (+rapid+ or +gradual+)
# @attr_reader delivery_options [Hash, nil] Delivery throttling options (+emails_per_hour+)
# @attr_reader subscription_topic_id [Integer, nil] ID of the campaign's subscription topic,
# as returned by {SubscriptionTopicsAPI}, or +nil+ when it has none
# @attr_reader template [Hash, nil] The campaign template (+id+, +subject+, +merge_tags+,
# +body_html+, +body_text+; bodies are omitted on list responses)
EmailCampaign = Struct.new(
Expand All @@ -81,6 +83,7 @@ module Mailtrap
:contact_segment_ids,
:delivery_mode,
:delivery_options,
:subscription_topic_id,
:template,
keyword_init: true
)
Expand Down
7 changes: 7 additions & 0 deletions lib/mailtrap/email_campaigns_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class EmailCampaignsAPI
delivery_options
contact_list_ids
contact_segment_ids
subscription_topic_id
].freeze

self.response_class = EmailCampaign
Expand Down Expand Up @@ -70,6 +71,9 @@ def get(email_campaign_id)
# applies when +delivery_mode+ is +gradual+
# @option options [Array<Integer>] :contact_list_ids IDs of contact lists to send to
# @option options [Array<Integer>] :contact_segment_ids IDs of contact segments to send to
# @option options [Integer] :subscription_topic_id ID of the subscription topic,
# as returned by {SubscriptionTopicsAPI}; must cover the campaign's domain.
# Ignored on an account without subscription topics
# @return [EmailCampaign] Created email campaign
# @!macro api_errors
# @raise [ArgumentError] If invalid options are provided
Expand All @@ -94,6 +98,9 @@ def create(options)
# applies when +delivery_mode+ is +gradual+
# @option options [Array<Integer>] :contact_list_ids IDs of contact lists to send to
# @option options [Array<Integer>] :contact_segment_ids IDs of contact segments to send to
# @option options [Integer] :subscription_topic_id ID of the subscription topic,
# as returned by {SubscriptionTopicsAPI}; it can be changed but not removed, so +nil+ is rejected.
# Ignored on an account without subscription topics
# @return [EmailCampaign] Updated email campaign
# @!macro api_errors
# @raise [ArgumentError] If invalid options are provided
Expand Down
5 changes: 3 additions & 2 deletions lib/mailtrap/email_log_event.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@ module Mailtrap
# Data Transfer Object for an email log event (delivery, open, click, bounce, etc.)
# @see https://docs.mailtrap.io/developers/email-sending/email-logs
# @attr_reader event_type [String] One of: delivery, open, click, soft_bounce, bounce, spam, unsubscribe, suspension,
# reject
# reject, topic_unsubscribe, topic_resubscribe; a type added to the API later is passed through as is
# @attr_reader created_at [String] ISO 8601 timestamp
# @attr_reader details [EmailLogEventDetails::Delivery, EmailLogEventDetails::Open, EmailLogEventDetails::Click,
# EmailLogEventDetails::Bounce, EmailLogEventDetails::Spam, EmailLogEventDetails::Unsubscribe,
# EmailLogEventDetails::Reject] Type-specific event details
# EmailLogEventDetails::Reject, EmailLogEventDetails::TopicSubscription, Hash] Type-specific event details;
# a Hash for an event type this version doesn't know
EmailLogEvent = Struct.new(
:event_type,
:created_at,
Expand Down
Loading
Loading