From 2aea08120fb2786ae0ae96eabafb6fd6adadcdb8 Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Fri, 20 Nov 2026 13:58:41 +0100 Subject: [PATCH 1/3] Add Subscription Topics and topic fields SubscriptionTopicsAPI lists and gets the account's topics, and campaigns, contacts, contact imports, suppressions, email logs and webhooks carry the topic fields, so topics can be used without raw HTTP calls. An email-log event type the gem doesn't know now keeps its details as a Hash instead of raising, so a newer event doesn't fail the whole message. A 5xx with a JSON body raises its errors rather than "server error", so the contacts 503 that names the contact to update reaches the caller. An empty 403, as accounts without topics get, raises "forbidden" even when the body is declared JSON. Co-Authored-By: Claude Opus 5.5 --- README.md | 1 + examples/contacts_api.rb | 34 ++++++ examples/email_campaigns_api.rb | 12 ++ examples/email_logs_api.rb | 13 ++- examples/subscription_topics_api.rb | 35 ++++++ examples/suppressions_api.rb | 7 ++ examples/webhooks_api.rb | 13 +++ lib/mailtrap.rb | 1 + lib/mailtrap/client.rb | 13 ++- lib/mailtrap/contact.rb | 4 + lib/mailtrap/contact_imports_api.rb | 6 +- lib/mailtrap/contacts_api.rb | 14 ++- lib/mailtrap/contacts_import_request.rb | 15 +++ lib/mailtrap/email_campaign.rb | 3 + lib/mailtrap/email_campaigns_api.rb | 7 ++ lib/mailtrap/email_log_event.rb | 5 +- lib/mailtrap/email_log_event_details.rb | 16 ++- lib/mailtrap/subscription_topic.rb | 34 ++++++ lib/mailtrap/subscription_topics_api.rb | 56 ++++++++++ lib/mailtrap/suppression.rb | 5 +- lib/mailtrap/suppressions_api.rb | 11 +- lib/mailtrap/webhook.rb | 5 +- lib/mailtrap/webhooks_api.rb | 9 +- spec/mailtrap/client_spec.rb | 33 ++++++ spec/mailtrap/contact_imports_api_spec.rb | 19 ++++ spec/mailtrap/contact_spec.rb | 7 +- spec/mailtrap/contacts_api_spec.rb | 102 +++++++++++++++++ spec/mailtrap/contacts_import_request_spec.rb | 32 ++++++ spec/mailtrap/email_campaign_spec.rb | 2 + spec/mailtrap/email_campaigns_api_spec.rb | 44 +++++++- spec/mailtrap/email_log_event_details_spec.rb | 22 ++-- spec/mailtrap/email_logs_api_spec.rb | 45 ++++++++ spec/mailtrap/subscription_topic_spec.rb | 33 ++++++ spec/mailtrap/subscription_topics_api_spec.rb | 105 ++++++++++++++++++ spec/mailtrap/suppression_spec.rb | 1 + spec/mailtrap/suppressions_api_spec.rb | 41 +++++++ spec/mailtrap/webhooks_api_spec.rb | 27 +++++ 37 files changed, 798 insertions(+), 34 deletions(-) create mode 100644 examples/subscription_topics_api.rb create mode 100644 lib/mailtrap/subscription_topic.rb create mode 100644 lib/mailtrap/subscription_topics_api.rb create mode 100644 spec/mailtrap/subscription_topic_spec.rb create mode 100644 spec/mailtrap/subscription_topics_api_spec.rb diff --git a/README.md b/README.md index e8aa121e..dce44f81 100644 --- a/README.md +++ b/README.md @@ -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: diff --git a/examples/contacts_api.rb b/examples/contacts_api.rb index 27532636..1793a277 100644 --- a/examples/contacts_api.rb +++ b/examples/contacts_api.rb @@ -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. +begin + topic = Mailtrap::SubscriptionTopicsAPI.new(client).list.data.first + if topic + domain_id = topic.domain_id || Mailtrap::DomainsAPI.new(account_id, client).list.first&.id + topic_contact = contacts.upsert( + contact.id, + subscription_topics: [{ subscription_topic_id: topic.id, domain_id:, status: 'unsubscribed' }] + ) + topic_contact.subscription_topics + # => [{ subscription_topic_id: 12, domain_id: 4321, status: "unsubscribed" }, ...] + end +rescue Mailtrap::RejectionError + puts 'Subscription topics are not available for this account' +end +# Without subscription topics, Contact#subscription_topics is nil and setting them raises +# Mailtrap::Error ("are not available for this account"). + # Remove contact from lists contacts.remove_from_lists(contact.id, [list.id]) # => # # +# 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| + 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 + # => # +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) diff --git a/examples/email_logs_api.rb b/examples/email_logs_api.rb index e76223b7..2a352715 100644 --- a/examples/email_logs_api.rb +++ b/examples/email_logs_api.rb @@ -50,5 +50,16 @@ # events=[#, ...]> 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 diff --git a/examples/subscription_topics_api.rb b/examples/subscription_topics_api.rb new file mode 100644 index 00000000..ca435e75 --- /dev/null +++ b/examples/subscription_topics_api.rb @@ -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) + # => #], + # pagination={:token=>1, :prev_token=>nil, :next_token=>2, ...}> + list.data + # => [#] + # 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 + # => # +rescue Mailtrap::RejectionError + puts 'Subscription topics are not available for this account' +end diff --git a/examples/suppressions_api.rb b/examples/suppressions_api.rb index e15e4762..8f06ab81 100644 --- a/examples/suppressions_api.rb +++ b/examples/suppressions_api.rb @@ -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) +# => [..., #] + # Add an email to the suppression list. # `type` is optional and defaults to 'manual import'. suppression = suppressions.create( diff --git a/examples/webhooks_api.rb b/examples/webhooks_api.rb index a02b66f8..e177841f 100644 --- a/examples/webhooks_api.rb +++ b/examples/webhooks_api.rb @@ -15,6 +15,19 @@ ) # => # +# 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', diff --git a/lib/mailtrap.rb b/lib/mailtrap.rb index f4889c94..e75073f5 100644 --- a/lib/mailtrap.rb +++ b/lib/mailtrap.rb @@ -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' diff --git a/lib/mailtrap/client.rb b/lib/mailtrap/client.rb index edc17536..23ab7f80 100644 --- a/lib/mailtrap/client.rb +++ b/lib/mailtrap/client.rb @@ -318,7 +318,7 @@ 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 @@ -326,7 +326,7 @@ def handle_response(response) # rubocop:disable Metrics/CyclomaticComplexity, Me 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 @@ -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'] + end + def json_response?(response) response.content_type == 'application/json' end diff --git a/lib/mailtrap/contact.rb b/lib/mailtrap/contact.rb index 780be638..bc86b3f4 100644 --- a/lib/mailtrap/contact.rb +++ b/lib/mailtrap/contact.rb @@ -10,6 +10,9 @@ 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, nil] The contact's subscription topic preferences, + # each +{ subscription_topic_id:, domain_id:, status: }+ with +status+ +subscribed+ or +unsubscribed+. + # +nil+ when the account has no subscription topics, or when they could not be read (retry then) Contact = Struct.new( :id, :email, @@ -18,6 +21,7 @@ module Mailtrap :status, :created_at, :updated_at, + :subscription_topics, keyword_init: true ) do def initialize(options) diff --git a/lib/mailtrap/contact_imports_api.rb b/lib/mailtrap/contact_imports_api.rb index 3b6a754e..8918fc25 100644 --- a/lib/mailtrap/contact_imports_api.rb +++ b/lib/mailtrap/contact_imports_api.rb @@ -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 @@ -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) # diff --git a/lib/mailtrap/contacts_api.rb b/lib/mailtrap/contacts_api.rb index 9af52eaa..e98a5663 100644 --- a/lib/mailtrap/contacts_api.rb +++ b/lib/mailtrap/contacts_api.rb @@ -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 @@ -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] :list_ids The contact's list IDs + # @option options [Array] :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 @@ -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] :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 diff --git a/lib/mailtrap/contacts_import_request.rb b/lib/mailtrap/contacts_import_request.rb index 731a507a..c34287be 100644 --- a/lib/mailtrap/contacts_import_request.rb +++ b/lib/mailtrap/contacts_import_request.rb @@ -47,6 +47,21 @@ def remove_from_lists(email:, list_ids:) self end + # Sets the contact's subscription topic preferences; preferences left out keep their status. + # Importing them fails on an account without subscription topics. + # @param email [String] The contact's email address + # @param subscription_topics [Array] 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? + + @data[email][:subscription_topics] = Array(@data[email][:subscription_topics]) | subscription_topics + + self + end + # @return [Array] Array of contact objects ready for import def to_a @data.values diff --git a/lib/mailtrap/email_campaign.rb b/lib/mailtrap/email_campaign.rb index 5db110cf..2f919f05 100644 --- a/lib/mailtrap/email_campaign.rb +++ b/lib/mailtrap/email_campaign.rb @@ -60,6 +60,8 @@ module Mailtrap # @attr_reader contact_segment_ids [Array] 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( @@ -81,6 +83,7 @@ module Mailtrap :contact_segment_ids, :delivery_mode, :delivery_options, + :subscription_topic_id, :template, keyword_init: true ) diff --git a/lib/mailtrap/email_campaigns_api.rb b/lib/mailtrap/email_campaigns_api.rb index 5442bc49..7a66603b 100644 --- a/lib/mailtrap/email_campaigns_api.rb +++ b/lib/mailtrap/email_campaigns_api.rb @@ -18,6 +18,7 @@ class EmailCampaignsAPI delivery_options contact_list_ids contact_segment_ids + subscription_topic_id ].freeze self.response_class = EmailCampaign @@ -70,6 +71,9 @@ def get(email_campaign_id) # applies when +delivery_mode+ is +gradual+ # @option options [Array] :contact_list_ids IDs of contact lists to send to # @option options [Array] :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 @@ -94,6 +98,9 @@ def create(options) # applies when +delivery_mode+ is +gradual+ # @option options [Array] :contact_list_ids IDs of contact lists to send to # @option options [Array] :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 diff --git a/lib/mailtrap/email_log_event.rb b/lib/mailtrap/email_log_event.rb index e3376469..647b3a25 100644 --- a/lib/mailtrap/email_log_event.rb +++ b/lib/mailtrap/email_log_event.rb @@ -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, diff --git a/lib/mailtrap/email_log_event_details.rb b/lib/mailtrap/email_log_event_details.rb index 20ab0060..8b090567 100644 --- a/lib/mailtrap/email_log_event_details.rb +++ b/lib/mailtrap/email_log_event_details.rb @@ -33,6 +33,9 @@ module EmailLogEventDetails # For event_type = suspension or reject Reject = Struct.new(:reject_reason, keyword_init: true) + # For event_type = topic_unsubscribe or topic_resubscribe + TopicSubscription = Struct.new(:web_ip_address, :subscription_topic_id, keyword_init: true) + DETAIL_STRUCTS = { 'delivery' => Delivery, 'open' => Open, @@ -42,17 +45,20 @@ module EmailLogEventDetails 'spam' => Spam, 'unsubscribe' => Unsubscribe, 'suspension' => Reject, - 'reject' => Reject + 'reject' => Reject, + 'topic_unsubscribe' => TopicSubscription, + 'topic_resubscribe' => TopicSubscription }.freeze # Builds the appropriate detail struct from API response. - # @param event_type [String] Known event type (delivery, open, click, etc.) + # @param event_type [String] Event type (delivery, open, click, etc.) # @param hash [Hash] Symbol-keyed details from parsed JSON - # @return [Delivery, Open, Click, Bounce, Spam, Unsubscribe, Reject] - # @raise [ArgumentError] when event_type is nil or not in DETAIL_STRUCTS + # @return [Delivery, Open, Click, Bounce, Spam, Unsubscribe, Reject, TopicSubscription, Hash, nil] + # For an event type not in DETAIL_STRUCTS, the details as returned, so a newer event type doesn't fail + # the whole message def self.build(event_type, hash) struct_class = DETAIL_STRUCTS[event_type.to_s] - raise ArgumentError, "Unknown event_type: #{event_type.inspect}" unless struct_class + return hash unless struct_class attrs = hash.slice(*struct_class.members) struct_class.new(**attrs) diff --git a/lib/mailtrap/subscription_topic.rb b/lib/mailtrap/subscription_topic.rb new file mode 100644 index 00000000..8f0898e9 --- /dev/null +++ b/lib/mailtrap/subscription_topic.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +module Mailtrap + # Data Transfer Object for Subscription Topic + # @attr_reader id [Integer] The subscription topic ID + # @attr_reader name [String] The topic name + # @attr_reader description [String, nil] The topic description + # @attr_reader domain_id [Integer, nil] ID of the sending domain the topic is limited to, + # as returned by the Domains endpoints; +nil+ when it covers every domain + # @attr_reader deleted_at [String, nil] When the topic was deleted; set only on a deleted topic, + # which {SubscriptionTopicsAPI#get} still returns + # @attr_reader created_at [String] The creation timestamp + # @attr_reader updated_at [String] The last update timestamp + SubscriptionTopic = Struct.new( + :id, + :name, + :description, + :domain_id, + :deleted_at, + :created_at, + :updated_at, + keyword_init: true + ) + + # Response from listing subscription topics (paginated) + # @attr_reader data [Array] Page of subscription topics, by ID + # @attr_reader pagination [Hash] Page-token pagination metadata + # (+token+, +prev_token+, +next_token+, +first_url+, +prev_url+, +current_url+, +next_url+) + SubscriptionTopicsListResponse = Struct.new( + :data, + :pagination, + keyword_init: true + ) +end diff --git a/lib/mailtrap/subscription_topics_api.rb b/lib/mailtrap/subscription_topics_api.rb new file mode 100644 index 00000000..94cf4dc5 --- /dev/null +++ b/lib/mailtrap/subscription_topics_api.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require_relative 'base_api' +require_relative 'subscription_topic' + +module Mailtrap + # Read-only: subscription topics are managed in the Mailtrap app. Use a topic's ID as + # +subscription_topic_id+ on email campaigns and in contacts' +subscription_topics+. + class SubscriptionTopicsAPI + include BaseAPI + + self.response_class = SubscriptionTopic + + # @param client [Mailtrap::Client] The client instance + def initialize(client = Mailtrap::Client.new) + @client = client + end + + # Lists the account's subscription topics by ID, one page at a time; deleted topics are left out. + # Pass +pagination[:next_token]+ with the same +per_page+ to get the next page. + # @param per_page [Integer, nil] Number of topics per page (max 100, default 50) + # @param token [Integer, nil] Page number to retrieve (page-token pagination, default 1) + # @return [SubscriptionTopicsListResponse] The page of topics and pagination metadata + # @!macro api_errors + def list(per_page: nil, token: nil) + query_params = {} + query_params[:per_page] = per_page unless per_page.nil? + query_params[:token] = token unless token.nil? + + response = client.get(base_path, query_params) + + SubscriptionTopicsListResponse.new( + data: Array(response[:data]).map { |item| build_entity(item, response_class) }, + pagination: response[:pagination] + ) + end + + # Retrieves a specific subscription topic, including a deleted one + # @param subscription_topic_id [Integer] The subscription topic ID + # @return [SubscriptionTopic] Subscription topic object + # @!macro api_errors + def get(subscription_topic_id) + base_get(subscription_topic_id) + end + + private + + def base_path + '/api/subscription_topics' + end + + def handle_response(response) + build_entity(response[:data], response_class) + end + end +end diff --git a/lib/mailtrap/suppression.rb b/lib/mailtrap/suppression.rb index eb3403a1..4458036a 100644 --- a/lib/mailtrap/suppression.rb +++ b/lib/mailtrap/suppression.rb @@ -4,11 +4,13 @@ module Mailtrap # Data Transfer Object for Suppression # @see https://api-docs.mailtrap.io/docs/mailtrap-api-docs/f8144826d885a-list-and-search-suppressions # @attr_reader id [String] The suppression UUID - # @attr_reader type [String] The suppression type + # @attr_reader type [String] The suppression type (+hard bounce+, +spam complaint+, +unsubscription+, + # +manual import+, or +topic unsubscription+ when listed with +include_topic_unsubscriptions+) # @attr_reader created_at [String] The creation timestamp # @attr_reader email [String] The email address # @attr_reader sending_stream [String] The sending stream # @attr_reader domain_name [String, nil] The domain name + # @attr_reader subscription_topic_id [Integer, nil] The subscription topic ID of a +topic unsubscription+ # @attr_reader message_bounce_category [String, nil] The bounce category # @attr_reader message_category [String, nil] The message category # @attr_reader message_client_ip [String, nil] The client IP @@ -26,6 +28,7 @@ module Mailtrap :email, :sending_stream, :domain_name, + :subscription_topic_id, :message_bounce_category, :message_category, :message_client_ip, diff --git a/lib/mailtrap/suppressions_api.rb b/lib/mailtrap/suppressions_api.rb index 33f0111a..53910548 100644 --- a/lib/mailtrap/suppressions_api.rb +++ b/lib/mailtrap/suppressions_api.rb @@ -13,11 +13,14 @@ class SuppressionsAPI # Lists all suppressions for the account # @param email [String] Email address to filter suppressions (optional) + # @param include_topic_unsubscriptions [Boolean] Whether to include the contacts' subscription topic + # unsubscriptions, of type +topic unsubscription+ (optional, default false) # @return [Array] Array of suppression objects # @!macro api_errors - def list(email: nil) + def list(email: nil, include_topic_unsubscriptions: false) query_params = {} query_params[:email] = email if email + query_params[:include_topic_unsubscriptions] = true if include_topic_unsubscriptions base_list(query_params) end @@ -27,7 +30,8 @@ def list(email: nil) # @option options [String] :email Email address to suppress # @option options [Integer] :domain_id ID of the domain to suppress this email for # @option options [String] :sending_stream The sending stream to suppress for: "transactional" or "bulk" - # @option options [String] :type Reason for the suppression, defaults to "manual import" when omitted + # @option options [String] :type Reason for the suppression, defaults to "manual import" when omitted. + # A +topic unsubscription+ is only listed, not created # @return [Suppression] Created suppression # @!macro api_errors # @raise [ArgumentError] If invalid options are provided @@ -37,7 +41,8 @@ def create(options) build_entity(response[:data], Suppression) end - # Deletes a suppression + # Deletes a suppression. A +topic unsubscription+ cannot be deleted: resubscribe the contact + # with +subscription_topics+ in {ContactsAPI#upsert} instead # @param suppression_id [String] The suppression UUID # @return [Suppression] The deleted suppression # @!macro api_errors diff --git a/lib/mailtrap/webhook.rb b/lib/mailtrap/webhook.rb index 617d7aeb..447ca573 100644 --- a/lib/mailtrap/webhook.rb +++ b/lib/mailtrap/webhook.rb @@ -15,8 +15,9 @@ module Mailtrap # or nil for all domains. Applicable only for `email_sending` webhooks. # @attr_reader inbound_inbox_id [Integer, nil] The inbound inbox ID the webhook is linked to. # Applicable only for `inbound_receiving` webhooks. - # @attr_reader event_types [Array] The event types the webhook is subscribed to. - # Applicable only for `email_sending` webhooks. + # @attr_reader event_types [Array] The event types the webhook is subscribed to + # (`delivery`, `soft_bounce`, `bounce`, `suspension`, `unsubscribe`, `open`, `spam_complaint`, `click`, + # `reject`, `subscription_preferences_update`). Applicable only for `email_sending` and `campaigns` webhooks. # @attr_reader signing_secret [String, nil] HMAC SHA-256 signing secret. Returned only on creation. Webhook = Struct.new( :id, diff --git a/lib/mailtrap/webhooks_api.rb b/lib/mailtrap/webhooks_api.rb index fc5ec661..db6437a7 100644 --- a/lib/mailtrap/webhooks_api.rb +++ b/lib/mailtrap/webhooks_api.rb @@ -37,8 +37,9 @@ def get(webhook_id) # @option options [String] :payload_format Payload format (`json` or `jsonlines`). Defaults to `json`. # @option options [String] :sending_stream Sending stream (`transactional` or `bulk`). # Required for `email_sending` webhook type. - # @option options [Array] :event_types Event types to subscribe to. - # Required for `email_sending` webhook type. + # @option options [Array] :event_types Event types to subscribe to, see {Webhook#event_types}. + # Required for `email_sending` and `campaigns` webhook types. `subscription_preferences_update` + # is available only for `campaigns` webhooks and `email_sending` webhooks of the `bulk` stream. # @option options [Integer] :domain_id Domain ID to scope the webhook to. # Applicable only for `email_sending` webhooks. # @option options [Integer] :inbound_inbox_id Inbound inbox ID to link the webhook to. @@ -57,8 +58,8 @@ def create(options) # @option options [String] :url The URL that will receive webhook payloads # @option options [Boolean] :active Whether the webhook is active # @option options [String] :payload_format Payload format (`json` or `jsonlines`) - # @option options [Array] :event_types Event types to subscribe to. - # Applicable only for `email_sending` webhooks. + # @option options [Array] :event_types Event types to subscribe to, see {#create}. + # Applicable only for `email_sending` and `campaigns` webhooks. # @option options [Integer] :inbound_inbox_id Inbound inbox ID to link the webhook to. # Applicable only for `inbound_receiving` webhooks. # @return [Webhook] Updated webhook diff --git a/spec/mailtrap/client_spec.rb b/spec/mailtrap/client_spec.rb index 5246724d..bfe5b8f7 100644 --- a/spec/mailtrap/client_spec.rb +++ b/spec/mailtrap/client_spec.rb @@ -268,12 +268,45 @@ def stub_post(path, status, body) end end + it 'handles general API 403 with empty response body' do + stub_post %r{/api/test}, 403, '' do + expect { client.post('/api/test') }.to raise_error(Mailtrap::RejectionError, 'forbidden') + end + end + it 'handles server errors' do stub_api_send 504, '🫖' do expect { send_mail }.to raise_error(Mailtrap::Error, 'server error') end end + it 'handles server errors with the errors of a JSON body' do + message = 'The contact was saved, but its subscription topic preferences were not.' + stub = stub_request(:post, %r{/api/test}) + .to_return( + status: 503, body: { errors: message }.to_json, headers: { 'Content-Type' => 'application/json' } + ) + + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, message) + expect(stub).to have_been_requested + end + + it 'handles server errors with a JSON body without errors' do + stub = stub_request(:post, %r{/api/test}) + .to_return(status: 500, body: '[]', headers: { 'Content-Type' => 'application/json' }) + + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') + expect(stub).to have_been_requested + end + + it 'handles server errors with an HTML body' do + stub = stub_request(:post, %r{/api/test}) + .to_return(status: 502, body: 'Bad Gateway', headers: { 'Content-Type' => 'text/html' }) + + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') + expect(stub).to have_been_requested + end + it 'handles unexpected response status code' do stub_api_send 307 do expect { send_mail }.to raise_error(Mailtrap::Error, 'unexpected status code=307') diff --git a/spec/mailtrap/contact_imports_api_spec.rb b/spec/mailtrap/contact_imports_api_spec.rb index b96fb79d..64b30e10 100644 --- a/spec/mailtrap/contact_imports_api_spec.rb +++ b/spec/mailtrap/contact_imports_api_spec.rb @@ -70,6 +70,25 @@ ) end + it 'sends subscription topic preferences' do + contacts = [ + { + email: 'j.doe@example.com', + subscription_topics: [{ subscription_topic_id: 12, domain_id: 4321, status: 'unsubscribed' }] + } + ] + stub = stub_request(:post, %r{/api/accounts/123/contacts/imports}) + .with(body: { contacts: }.to_json) + .to_return( + status: 200, + body: { id: 1, status: 'started' }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + imports_api.create(contacts) + expect(stub).to have_been_requested + end + it 'validates contacts' do expect { imports_api.create([{ email: 'john@example.com', foo: 1 }]) }.to raise_error(ArgumentError) end diff --git a/spec/mailtrap/contact_spec.rb b/spec/mailtrap/contact_spec.rb index 19982fec..7e7956a5 100644 --- a/spec/mailtrap/contact_spec.rb +++ b/spec/mailtrap/contact_spec.rb @@ -13,10 +13,15 @@ list_ids: [1, 2], status: 'subscribed', created_at: 1_700_000_000, - updated_at: 1_700_000_100 + updated_at: 1_700_000_100, + subscription_topics: [{ subscription_topic_id: 12, domain_id: 4321, status: 'unsubscribed' }] } end + it 'creates a contact with all attributes' do + expect(contact).to have_attributes(attributes) + end + describe '#newly_created?' do it { is_expected.to be_newly_created } diff --git a/spec/mailtrap/contacts_api_spec.rb b/spec/mailtrap/contacts_api_spec.rb index 347847b1..61dfcb80 100644 --- a/spec/mailtrap/contacts_api_spec.rb +++ b/spec/mailtrap/contacts_api_spec.rb @@ -87,6 +87,47 @@ end end + context 'with subscription topics' do + let(:subscription_topics) do + [ + { 'subscription_topic_id' => 12, 'domain_id' => 4321, 'status' => 'subscribed' }, + { 'subscription_topic_id' => 12, 'domain_id' => 4322, 'status' => 'unsubscribed' } + ] + end + + def stub_contact(data) + stub_request(:get, "#{base_url}/contacts/#{contact_id}") + .to_return( + status: 200, + body: { 'data' => { 'id' => contact_id, 'email' => email }.merge(data) }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + end + + it 'returns the contact preferences' do + stub_contact('subscription_topics' => subscription_topics) + + expect(client.get(contact_id).subscription_topics).to eq( + [ + { subscription_topic_id: 12, domain_id: 4321, status: 'subscribed' }, + { subscription_topic_id: 12, domain_id: 4322, status: 'unsubscribed' } + ] + ) + end + + it 'returns nil when the preferences could not be read' do + stub_contact('subscription_topics' => nil) + + expect(client.get(contact_id).subscription_topics).to be_nil + end + + it 'returns nil when the account has no subscription topics' do + stub_contact({}) + + expect(client.get(contact_id)).to have_attributes(email:, subscription_topics: nil) + end + end + context 'when contact is not found' do it 'raises error for non-existent UUID' do stub_request(:get, "#{base_url}/contacts/non-existent-uuid") @@ -169,6 +210,50 @@ expect { client.create(invalid_data) }.to raise_error(Mailtrap::Error) end + + context 'with subscription topics' do + let(:subscription_topics) { [{ subscription_topic_id: 12, domain_id: 4321, status: 'unsubscribed' }] } + let(:contact_data) { { email:, subscription_topics: } } + + it 'sends them and returns the contact preferences' do + stub = stub_request(:post, "#{base_url}/contacts") + .with(body: { contact: contact_data }.to_json) + .to_return( + status: 201, + body: { 'data' => expected_response['data'].merge('subscription_topics' => subscription_topics) } + .to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + response = client.create(contact_data) + expect(stub).to have_been_requested + expect(response.subscription_topics).to eq(subscription_topics) + end + + it 'raises error when the account has no subscription topics' do + stub_request(:post, "#{base_url}/contacts") + .to_return( + status: 422, + body: { 'errors' => { 'subscription_topics' => ['are not available for this account'] } }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + expect { client.create(contact_data) }.to raise_error(Mailtrap::Error, /are not available for this account/) + end + + it 'raises error naming the contact when the preferences were not saved' do + message = 'The contact was saved, but its subscription topic preferences were not. ' \ + "Send them again in an update of contact #{contact_id}." + stub_request(:post, "#{base_url}/contacts") + .to_return( + status: 503, + body: { 'errors' => message }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + expect { client.create(contact_data) }.to raise_error(Mailtrap::Error, message) + end + end end describe '#update' do @@ -233,6 +318,23 @@ expect(response).to have_attributes(email:) expect(response.newly_created?).to be false end + + it 'changes only the subscription topic preferences' do + subscription_topics = [{ subscription_topic_id: 12, domain_id: 4321, status: 'subscribed' }] + stub = stub_request(:patch, "#{base_url}/contacts/#{contact_id}") + .with(body: { contact: { subscription_topics: } }.to_json) + .to_return( + status: 200, + body: expected_response.merge( + 'data' => expected_response['data'].merge('subscription_topics' => subscription_topics) + ).to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + response = client.upsert(contact_id, subscription_topics:) + expect(stub).to have_been_requested + expect(response.subscription_topics).to eq(subscription_topics) + end end # rubocop:enable RSpec/MultipleMemoizedHelpers diff --git a/spec/mailtrap/contacts_import_request_spec.rb b/spec/mailtrap/contacts_import_request_spec.rb index 37b36cbf..7193bc67 100644 --- a/spec/mailtrap/contacts_import_request_spec.rb +++ b/spec/mailtrap/contacts_import_request_spec.rb @@ -76,6 +76,38 @@ end end + describe '#update_subscription_topics' do + let(:subscribed) { { subscription_topic_id: 12, domain_id: 4321, status: 'subscribed' } } + let(:unsubscribed) { { subscription_topic_id: 13, domain_id: 4321, status: 'unsubscribed' } } + + it 'validates email' do + expect { described_class.new.update_subscription_topics(email: nil, subscription_topics: [subscribed]) } + .to raise_error(ArgumentError) + expect { described_class.new.update_subscription_topics(email: '', subscription_topics: [subscribed]) } + .to raise_error(ArgumentError) + end + + it 'does not allow empty list' do + expect { described_class.new.update_subscription_topics(email: 'one@example.com', subscription_topics: []) } + .to raise_error(ArgumentError) + end + + it 'sets the contact preferences' do + request = described_class.new.tap do |req| + req.update_subscription_topics(email: 'one@example.com', subscription_topics: [subscribed]) + .update_subscription_topics(email: 'one@example.com', subscription_topics: [subscribed, unsubscribed]) + .upsert(email: 'two@example.com') + end + expect(request.to_a).to contain_exactly( + { + email: 'one@example.com', fields: {}, list_ids_included: [], list_ids_excluded: [], + subscription_topics: [subscribed, unsubscribed] + }, + { email: 'two@example.com', fields: {}, list_ids_included: [], list_ids_excluded: [] } + ) + end + end + describe '#to_a' do it 'returns json array' do request = described_class.new diff --git a/spec/mailtrap/email_campaign_spec.rb b/spec/mailtrap/email_campaign_spec.rb index e0207dfd..3afb466f 100644 --- a/spec/mailtrap/email_campaign_spec.rb +++ b/spec/mailtrap/email_campaign_spec.rb @@ -24,6 +24,7 @@ contact_segment_ids: [12], delivery_mode: 'gradual', delivery_options: { emails_per_hour: 1000 }, + subscription_topic_id: 12, template: { id: 789, subject: 'Spring is here — 30% off', @@ -55,6 +56,7 @@ contact_list_ids: nil, contact_segment_ids: nil, recipient_total_count: nil, + subscription_topic_id: nil, template: nil ) end diff --git a/spec/mailtrap/email_campaigns_api_spec.rb b/spec/mailtrap/email_campaigns_api_spec.rb index b245b2fe..cfc63b6a 100644 --- a/spec/mailtrap/email_campaigns_api_spec.rb +++ b/spec/mailtrap/email_campaigns_api_spec.rb @@ -19,6 +19,7 @@ 'delivery_mode' => 'rapid', 'delivery_options' => { 'emails_per_hour' => nil }, 'recipient_total_count' => nil, + 'subscription_topic_id' => 12, 'template' => { 'id' => 789, 'subject' => 'Spring is here — 30% off', @@ -50,7 +51,8 @@ domain_id: 4321, contact_list_ids: [55, 56], contact_segment_ids: [12], - delivery_mode: 'rapid' + delivery_mode: 'rapid', + subscription_topic_id: 12 ) expect(response.pagination).to eq(token: 1, prev_token: nil, next_token: nil) end @@ -95,6 +97,17 @@ expect(response).to have_attributes(id: 4567, name: 'Spring Sale', current_state: 'draft') end + it 'returns a campaign without a subscription topic' do + stub_request(:get, "#{base_url}/4567") + .to_return( + status: 200, + body: { 'data' => campaign_attributes.merge('subscription_topic_id' => nil) }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + expect(email_campaigns_api.get(4567).subscription_topic_id).to be_nil + end + it 'raises error when the campaign does not exist' do stub_request(:get, "#{base_url}/999") .to_return( @@ -119,7 +132,8 @@ delivery_mode: 'gradual', delivery_options: { emails_per_hour: 1000 }, contact_list_ids: [55, 56], - contact_segment_ids: [12] + contact_segment_ids: [12], + subscription_topic_id: 12 } end @@ -177,6 +191,32 @@ expect(response).to have_attributes(id: 4567, name: 'Spring Sale (updated)') end + it 'changes only the subscription topic' do + stub = stub_request(:patch, "#{base_url}/4567") + .with(body: { subscription_topic_id: 13 }.to_json) + .to_return( + status: 200, + body: { 'data' => campaign_attributes.merge('subscription_topic_id' => 13) }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + response = email_campaigns_api.update(4567, subscription_topic_id: 13) + expect(stub).to have_been_requested + expect(response.subscription_topic_id).to eq(13) + end + + it 'raises error when the subscription topic is invalid' do + stub_request(:patch, "#{base_url}/4567") + .to_return( + status: 422, + body: { 'errors' => { 'subscription_topic_id' => ['is invalid'] } }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + expect { email_campaigns_api.update(4567, subscription_topic_id: 13) } + .to raise_error(Mailtrap::Error, /subscription_topic_id/) + end + it 'raises ArgumentError when invalid options are provided' do expect { email_campaigns_api.update(4567, unknown_option: true) } .to raise_error(ArgumentError, /invalid options are given/) diff --git a/spec/mailtrap/email_log_event_details_spec.rb b/spec/mailtrap/email_log_event_details_spec.rb index aa53ac2f..249f915a 100644 --- a/spec/mailtrap/email_log_event_details_spec.rb +++ b/spec/mailtrap/email_log_event_details_spec.rb @@ -48,16 +48,22 @@ ) end - it 'raises ArgumentError for nil event_type with message referencing DETAIL_STRUCTS' do - expect { described_class.build(nil, {}) }.to raise_error( - ArgumentError, 'Unknown event_type: nil' - ) + %w[topic_unsubscribe topic_resubscribe].each do |event_type| + it "returns TopicSubscription struct for #{event_type} event_type" do + details = described_class.build(event_type, { web_ip_address: '198.51.100.50', subscription_topic_id: 12 }) + expect(details).to be_a(described_class::TopicSubscription) + expect(details).to have_attributes(web_ip_address: '198.51.100.50', subscription_topic_id: 12) + end end - it 'raises ArgumentError for unknown event_type with message listing known types' do - expect { described_class.build('unknown_type', {}) }.to raise_error( - ArgumentError, 'Unknown event_type: "unknown_type"' - ) + it 'returns the details hash for an unknown event_type' do + details = { web_ip_address: '198.51.100.50', new_detail: 'value' } + + expect(described_class.build('unknown_type', details)).to eq(details) + end + + it 'returns the details for a nil event_type' do + expect(described_class.build(nil, nil)).to be_nil end end end diff --git a/spec/mailtrap/email_logs_api_spec.rb b/spec/mailtrap/email_logs_api_spec.rb index be97c3c3..b9f4aeaa 100644 --- a/spec/mailtrap/email_logs_api_spec.rb +++ b/spec/mailtrap/email_logs_api_spec.rb @@ -192,6 +192,51 @@ ) end + context 'with subscription topic and unknown events', vcr: false do + let(:events) do + [ + { + event_type: 'topic_unsubscribe', + created_at: '2026-11-20T10:00:00Z', + details: { web_ip_address: '198.51.100.50', subscription_topic_id: 12 } + }, + { + event_type: 'topic_resubscribe', + created_at: '2026-11-20T11:00:00Z', + details: { web_ip_address: nil, subscription_topic_id: 12 } + }, + { event_type: 'future_event', created_at: '2026-11-20T12:00:00Z', details: { new_detail: 'value' } } + ] + end + + before do + stub_request(:get, "https://mailtrap.io/api/accounts/#{account_id}/email_logs/#{message_id}") + .to_return( + status: 200, + body: { message_id:, status: 'delivered', events: }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + end + + it 'maps the topic events and keeps the unknown event details' do + expect(message.events).to contain_exactly( + have_attributes( + event_type: 'topic_unsubscribe', + details: Mailtrap::EmailLogEventDetails::TopicSubscription.new( + web_ip_address: '198.51.100.50', subscription_topic_id: 12 + ) + ), + have_attributes( + event_type: 'topic_resubscribe', + details: Mailtrap::EmailLogEventDetails::TopicSubscription.new( + web_ip_address: nil, subscription_topic_id: 12 + ) + ), + have_attributes(event_type: 'future_event', details: { new_detail: 'value' }) + ) + end + end + context 'when message not found' do let(:message_id) { '00000000-0000-0000-0000-000000000000' } diff --git a/spec/mailtrap/subscription_topic_spec.rb b/spec/mailtrap/subscription_topic_spec.rb new file mode 100644 index 00000000..47f63859 --- /dev/null +++ b/spec/mailtrap/subscription_topic_spec.rb @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +RSpec.describe Mailtrap::SubscriptionTopic do + describe '#initialize' do + subject(:topic) { described_class.new(attributes) } + + let(:attributes) do + { + id: 12, + name: 'Product updates', + description: nil, + domain_id: 4321, + deleted_at: '2026-11-10T10:00:00Z', + created_at: '2026-11-01T10:00:00Z', + updated_at: '2026-11-10T10:00:00Z' + } + end + + it 'creates a subscription topic with all attributes' do + expect(topic).to have_attributes(attributes) + end + end + + describe Mailtrap::SubscriptionTopicsListResponse do + subject(:response) { described_class.new(data: [topic], pagination: { token: 1 }) } + + let(:topic) { Mailtrap::SubscriptionTopic.new(id: 12) } + + it 'exposes the page and its pagination' do + expect(response).to have_attributes(data: [topic], pagination: { token: 1 }) + end + end +end diff --git a/spec/mailtrap/subscription_topics_api_spec.rb b/spec/mailtrap/subscription_topics_api_spec.rb new file mode 100644 index 00000000..77786d40 --- /dev/null +++ b/spec/mailtrap/subscription_topics_api_spec.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +RSpec.describe Mailtrap::SubscriptionTopicsAPI do + subject(:subscription_topics_api) { described_class.new(Mailtrap::Client.new(api_key: 'correct-api-key')) } + + let(:base_url) { 'https://mailtrap.io/api/subscription_topics' } + let(:json_headers) { { 'Content-Type' => 'application/json' } } + let(:topic_attributes) do + { + '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' + } + end + + describe '#list' do + let(:pagination) do + { 'token' => 1, 'prev_token' => nil, 'next_token' => 2, 'first_url' => "#{base_url}?token=1" } + end + + it 'returns a paginated list of SubscriptionTopic objects' do + stub = stub_request(:get, base_url) + .to_return( + status: 200, + body: { 'data' => [topic_attributes], 'pagination' => pagination }.to_json, + headers: json_headers + ) + + response = subscription_topics_api.list + expect(stub).to have_been_requested + expect(response).to be_a(Mailtrap::SubscriptionTopicsListResponse) + expect(response.data).to contain_exactly( + Mailtrap::SubscriptionTopic.new(topic_attributes.transform_keys(&:to_sym)) + ) + expect(response.pagination).to eq(token: 1, prev_token: nil, next_token: 2, first_url: "#{base_url}?token=1") + end + + it 'passes pagination params' do + stub = stub_request(:get, base_url) + .with(query: { per_page: '10', token: '2' }) + .to_return( + status: 200, + body: { 'data' => [topic_attributes.merge('domain_id' => 4321)], 'pagination' => { 'token' => 2 } } + .to_json, + headers: json_headers + ) + + response = subscription_topics_api.list(per_page: 10, token: 2) + expect(stub).to have_been_requested + expect(response.data.first).to have_attributes(id: 12, domain_id: 4321) + end + + it 'raises RejectionError when the account has no subscription topics' do + stub_request(:get, base_url).to_return(status: 403, body: '') + + expect { subscription_topics_api.list }.to raise_error(Mailtrap::RejectionError, 'forbidden') + end + + it 'raises error when api key is incorrect' do + stub_request(:get, base_url) + .to_return(status: 401, body: { 'error' => 'Incorrect API token' }.to_json, headers: json_headers) + + expect { subscription_topics_api.list }.to raise_error(Mailtrap::AuthorizationError, /Incorrect API token/) + end + end + + describe '#get' do + it 'returns a SubscriptionTopic object' do + stub_request(:get, "#{base_url}/12") + .to_return(status: 200, body: { 'data' => topic_attributes }.to_json, headers: json_headers) + + response = subscription_topics_api.get(12) + expect(response).to be_a(Mailtrap::SubscriptionTopic) + expect(response).to have_attributes(id: 12, name: 'Product updates', domain_id: nil, deleted_at: nil) + end + + it 'returns a deleted topic' do + stub_request(:get, "#{base_url}/12") + .to_return( + status: 200, + body: { 'data' => topic_attributes.merge('deleted_at' => '2026-11-10T10:00:00Z') }.to_json, + headers: json_headers + ) + + expect(subscription_topics_api.get(12).deleted_at).to eq('2026-11-10T10:00:00Z') + end + + it 'raises RejectionError when the account has no subscription topics' do + stub_request(:get, "#{base_url}/12").to_return(status: 403, body: '', headers: json_headers) + + expect { subscription_topics_api.get(12) }.to raise_error(Mailtrap::RejectionError, 'forbidden') + end + + it 'raises error when the topic does not exist' do + stub_request(:get, "#{base_url}/999") + .to_return(status: 404, body: { 'error' => 'Not Found' }.to_json, headers: json_headers) + + expect { subscription_topics_api.get(999) }.to raise_error(Mailtrap::Error, /Not Found/) + end + end +end diff --git a/spec/mailtrap/suppression_spec.rb b/spec/mailtrap/suppression_spec.rb index b092a5a9..4d93e50c 100644 --- a/spec/mailtrap/suppression_spec.rb +++ b/spec/mailtrap/suppression_spec.rb @@ -9,6 +9,7 @@ email: 'test@example.com', sending_stream: 'main', domain_name: 'example.com', + subscription_topic_id: nil, message_bounce_category: 'hard_bounce', message_category: 'bounce', message_client_ip: '192.168.1.1', diff --git a/spec/mailtrap/suppressions_api_spec.rb b/spec/mailtrap/suppressions_api_spec.rb index b98e001d..8c3eadc3 100644 --- a/spec/mailtrap/suppressions_api_spec.rb +++ b/spec/mailtrap/suppressions_api_spec.rb @@ -31,6 +31,47 @@ end end + context 'with topic unsubscriptions', vcr: false do + let(:topic_unsubscription) do + { + id: 'c6a2f3a8-7d6e-4b8a-9f61-0d1e2f3a4b5c', + type: 'topic unsubscription', + created_at: '2026-11-20T10:00:00Z', + email: 'recipient@example.com', + sending_stream: 'bulk', + domain_name: 'example.com', + subscription_topic_id: 12 + } + end + + def stub_list(query, body) + stub_request(:get, "https://mailtrap.io/api/accounts/#{account_id}/suppressions#{query}") + .to_return(status: 200, body: body.to_json, headers: { 'Content-Type' => 'application/json' }) + end + + it 'requests them and maps the topic rows' do + stub = stub_list('?include_topic_unsubscriptions=true', [topic_unsubscription]) + + list = suppressions.list(include_topic_unsubscriptions: true) + expect(stub).to have_been_requested + expect(list).to contain_exactly(have_attributes(topic_unsubscription)) + end + + it 'combines them with the email filter' do + stub = stub_list('?email=recipient%40example.com&include_topic_unsubscriptions=true', []) + + suppressions.list(email: 'recipient@example.com', include_topic_unsubscriptions: true) + expect(stub).to have_been_requested + end + + it 'does not request them by default' do + stub = stub_list('', []) + + suppressions.list(include_topic_unsubscriptions: false) + expect(stub).to have_been_requested + end + end + context 'when api key is incorrect' do let(:client) { Mailtrap::Client.new(api_key: 'incorrect-api-key') } diff --git a/spec/mailtrap/webhooks_api_spec.rb b/spec/mailtrap/webhooks_api_spec.rb index 64ecca65..d29ea760 100644 --- a/spec/mailtrap/webhooks_api_spec.rb +++ b/spec/mailtrap/webhooks_api_spec.rb @@ -89,6 +89,33 @@ expect(create.signing_secret).not_to be_nil end + context 'when creating a campaigns webhook for subscription preference updates', vcr: false do + let(:request) do + { + url: 'https://example.com/mailtrap/campaigns', + webhook_type: 'campaigns', + payload_format: 'json', + event_types: %w[unsubscribe subscription_preferences_update] + } + end + + it 'sends and maps the event types' do + stub = stub_request(:post, "https://mailtrap.io/api/accounts/#{account_id}/webhooks") + .with(body: { webhook: request }.to_json) + .to_return( + status: 201, + body: { data: request.merge(id: 7, active: true, signing_secret: 'secret') }.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + expect(create).to have_attributes( + webhook_type: 'campaigns', + event_types: %w[unsubscribe subscription_preferences_update] + ) + expect(stub).to have_been_requested + end + end + context 'when creating an inbound_receiving webhook' do let(:request) do { From 70a070d46bca14ee9a4e3bfe28af0edb6aa7da6d Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 06:19:43 +0100 Subject: [PATCH 2/3] Keep one import preference per topic and domain The API rejects an import whose contact repeats a topic and domain, so a later update_subscription_topics call for the same pair now replaces the earlier preference instead of adding a second one. Contact#subscription_topics docs now tell an account without topic preferences (nil) from one without live topics (empty), and the contacts example no longer dies on the 422 an account gets when its topics are on but contact preferences are not. Co-Authored-By: Claude Opus 5.5 --- examples/contacts_api.rb | 25 +++++++++++-------- lib/mailtrap/contact.rb | 5 ++-- lib/mailtrap/contacts_import_request.rb | 17 +++++++++++-- spec/mailtrap/contacts_api_spec.rb | 2 +- spec/mailtrap/contacts_import_request_spec.rb | 20 +++++++++++++++ 5 files changed, 53 insertions(+), 16 deletions(-) diff --git a/examples/contacts_api.rb b/examples/contacts_api.rb index 1793a277..11c39554 100644 --- a/examples/contacts_api.rb +++ b/examples/contacts_api.rb @@ -117,22 +117,22 @@ # 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.data.first - if topic - domain_id = topic.domain_id || Mailtrap::DomainsAPI.new(account_id, client).list.first&.id + 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:, status: 'unsubscribed' }] + 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::RejectionError - puts 'Subscription topics are not available for this account' +rescue Mailtrap::Error => e + puts "Subscription topic preferences are not available: #{e.message}" end -# Without subscription topics, Contact#subscription_topics is nil and setting them raises -# Mailtrap::Error ("are not available for this account"). # Remove contact from lists contacts.remove_from_lists(contact.id, [list.id]) @@ -203,14 +203,17 @@ # Import subscription topic preferences, as for contacts.upsert above # (on an account without subscription topics, the import fails) -if topic - domain_id = topic.domain_id || Mailtrap::DomainsAPI.new(account_id, client).list.first&.id +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:, status: 'subscribed' }] + subscription_topics: [{ subscription_topic_id: topic.id, domain_id: topic_domain_id, status: 'subscribed' }] ) end - contact_imports.create(topics_import) + begin + contact_imports.create(topics_import) + rescue Mailtrap::Error => e + puts "Subscription topic preferences are not available: #{e.message}" + end end diff --git a/lib/mailtrap/contact.rb b/lib/mailtrap/contact.rb index bc86b3f4..2ca8068d 100644 --- a/lib/mailtrap/contact.rb +++ b/lib/mailtrap/contact.rb @@ -11,8 +11,9 @@ module Mailtrap # @attr_reader created_at [Integer] The creation timestamp # @attr_reader updated_at [Integer] The last update timestamp # @attr_reader subscription_topics [Array, nil] The contact's subscription topic preferences, - # each +{ subscription_topic_id:, domain_id:, status: }+ with +status+ +subscribed+ or +unsubscribed+. - # +nil+ when the account has no subscription topics, or when they could not be read (retry then) + # 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, diff --git a/lib/mailtrap/contacts_import_request.rb b/lib/mailtrap/contacts_import_request.rb index c34287be..43a28645 100644 --- a/lib/mailtrap/contacts_import_request.rb +++ b/lib/mailtrap/contacts_import_request.rb @@ -47,7 +47,8 @@ def remove_from_lists(email:, list_ids:) self end - # Sets the contact's subscription topic preferences; preferences left out keep their status. + # 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] Preferences, each +{ subscription_topic_id:, domain_id:, status: }+ @@ -57,7 +58,7 @@ def update_subscription_topics(email:, subscription_topics:) validate_email!(email) raise ArgumentError, 'subscription_topics must be present' if subscription_topics.empty? - @data[email][:subscription_topics] = Array(@data[email][:subscription_topics]) | subscription_topics + merge_subscription_topics(email:, subscription_topics:) self end @@ -78,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 diff --git a/spec/mailtrap/contacts_api_spec.rb b/spec/mailtrap/contacts_api_spec.rb index 61dfcb80..47914152 100644 --- a/spec/mailtrap/contacts_api_spec.rb +++ b/spec/mailtrap/contacts_api_spec.rb @@ -121,7 +121,7 @@ def stub_contact(data) expect(client.get(contact_id).subscription_topics).to be_nil end - it 'returns nil when the account has no subscription topics' do + it 'returns nil when subscription topics are not available for the account' do stub_contact({}) expect(client.get(contact_id)).to have_attributes(email:, subscription_topics: nil) diff --git a/spec/mailtrap/contacts_import_request_spec.rb b/spec/mailtrap/contacts_import_request_spec.rb index 7193bc67..54692c0a 100644 --- a/spec/mailtrap/contacts_import_request_spec.rb +++ b/spec/mailtrap/contacts_import_request_spec.rb @@ -106,6 +106,26 @@ { email: 'two@example.com', fields: {}, list_ids_included: [], list_ids_excluded: [] } ) end + + it 'keeps the latest preference for a topic and domain' do + request = described_class.new.tap do |req| + req.update_subscription_topics(email: 'one@example.com', subscription_topics: [subscribed, unsubscribed]) + .update_subscription_topics( + email: 'one@example.com', + subscription_topics: [ + { 'subscription_topic_id' => 12, 'domain_id' => 4321, 'status' => 'unsubscribed' }, + subscribed.merge(domain_id: 4322) + ] + ) + end + expect(request.to_a.first[:subscription_topics]).to eq( + [ + { subscription_topic_id: 12, domain_id: 4321, status: 'unsubscribed' }, + unsubscribed, + { subscription_topic_id: 12, domain_id: 4322, status: 'subscribed' } + ] + ) + end end describe '#to_a' do From 98cc65426411f60ae6858d42b5b307959499b04f Mon Sep 17 00:00:00 2001 From: Maciej Walusiak Date: Mon, 23 Nov 2026 06:22:15 +0100 Subject: [PATCH 3/3] Reuse the spec's post stub for the server error cases Also point the webhook update docs straight at Webhook#event_types and fetch a single topic in the contacts example, which uses only the first. Co-Authored-By: Claude Opus 5.5 --- examples/contacts_api.rb | 2 +- lib/mailtrap/webhooks_api.rb | 2 +- spec/mailtrap/client_spec.rb | 30 +++++++++++------------------- 3 files changed, 13 insertions(+), 21 deletions(-) diff --git a/examples/contacts_api.rb b/examples/contacts_api.rb index 11c39554..f90c34bb 100644 --- a/examples/contacts_api.rb +++ b/examples/contacts_api.rb @@ -120,7 +120,7 @@ # 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.data.first + 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( diff --git a/lib/mailtrap/webhooks_api.rb b/lib/mailtrap/webhooks_api.rb index db6437a7..685f0577 100644 --- a/lib/mailtrap/webhooks_api.rb +++ b/lib/mailtrap/webhooks_api.rb @@ -58,7 +58,7 @@ def create(options) # @option options [String] :url The URL that will receive webhook payloads # @option options [Boolean] :active Whether the webhook is active # @option options [String] :payload_format Payload format (`json` or `jsonlines`) - # @option options [Array] :event_types Event types to subscribe to, see {#create}. + # @option options [Array] :event_types Event types to subscribe to, see {Webhook#event_types}. # Applicable only for `email_sending` and `campaigns` webhooks. # @option options [Integer] :inbound_inbox_id Inbound inbox ID to link the webhook to. # Applicable only for `inbound_receiving` webhooks. diff --git a/spec/mailtrap/client_spec.rb b/spec/mailtrap/client_spec.rb index bfe5b8f7..10edf2ea 100644 --- a/spec/mailtrap/client_spec.rb +++ b/spec/mailtrap/client_spec.rb @@ -210,8 +210,8 @@ def stub_api_send(status, body = nil, &block) stub_post(%r{/api/send}, status, body, &block) end - def stub_post(path, status, body) - stub = stub_request(:post, path).to_return(status:, body:) + def stub_post(path, status, body, headers: {}) + stub = stub_request(:post, path).to_return(status:, body:, headers:) yield expect(stub).to have_been_requested end @@ -282,29 +282,21 @@ def stub_post(path, status, body) it 'handles server errors with the errors of a JSON body' do message = 'The contact was saved, but its subscription topic preferences were not.' - stub = stub_request(:post, %r{/api/test}) - .to_return( - status: 503, body: { errors: message }.to_json, headers: { 'Content-Type' => 'application/json' } - ) - - expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, message) - expect(stub).to have_been_requested + stub_post %r{/api/test}, 503, { errors: message }.to_json, headers: { 'Content-Type' => 'application/json' } do + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, message) + end end it 'handles server errors with a JSON body without errors' do - stub = stub_request(:post, %r{/api/test}) - .to_return(status: 500, body: '[]', headers: { 'Content-Type' => 'application/json' }) - - expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') - expect(stub).to have_been_requested + stub_post %r{/api/test}, 500, '[]', headers: { 'Content-Type' => 'application/json' } do + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') + end end it 'handles server errors with an HTML body' do - stub = stub_request(:post, %r{/api/test}) - .to_return(status: 502, body: 'Bad Gateway', headers: { 'Content-Type' => 'text/html' }) - - expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') - expect(stub).to have_been_requested + stub_post %r{/api/test}, 502, 'Bad Gateway', headers: { 'Content-Type' => 'text/html' } do + expect { client.post('/api/test') }.to raise_error(Mailtrap::Error, 'server error') + end end it 'handles unexpected response status code' do