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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,7 @@ Contact management:
Email marketing:
- Email campaigns CRUD, listing, lifecycle & stats – [`email-campaigns/all.php`](examples/email-campaigns/all.php)
- Email marketing stats (campaigns & automations) – [`marketing-stats/all.php`](examples/marketing-stats/all.php)
- Subscription topics (list & get) – [`subscription-topics/all.php`](examples/subscription-topics/all.php)

General API:
- Templates CRUD, paginated (experimental) – [`templates/templates.php`](examples/templates/templates.php)
Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Central index of runnable example scripts demonstrating Mailtrap PHP SDK feature
| Custom fields CRUD | [`contact-fields/all.php`](contact-fields/all.php) |
| Email campaigns CRUD + list + lifecycle + stats | [`email-campaigns/all.php`](email-campaigns/all.php) |
| Email marketing stats (campaigns + automations) | [`marketing-stats/all.php`](marketing-stats/all.php) |
| Subscription topics list + get | [`subscription-topics/all.php`](subscription-topics/all.php) |

### Templates & Domains

Expand Down
71 changes: 68 additions & 3 deletions examples/contacts/all.php
Original file line number Diff line number Diff line change
@@ -1,22 +1,54 @@
<?php

use Mailtrap\Config;
use Mailtrap\DTO\Request\Contact\ContactSubscriptionTopic;
use Mailtrap\DTO\Request\Contact\CreateContact;
use Mailtrap\DTO\Request\Contact\CreateContactEvent;
use Mailtrap\DTO\Request\Contact\ImportContact;
use Mailtrap\DTO\Request\Contact\UpdateContact;
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapGeneralClient;
use Mailtrap\MailtrapSendingClient;
use Mailtrap\DTO\Request\Contact\ContactExportFilter;

require __DIR__ . '/../../vendor/autoload.php';

$accountId = $_ENV['MAILTRAP_ACCOUNT_ID'];
$config = new Config($_ENV['MAILTRAP_API_KEY']); #your API token from here https://mailtrap.io/api-tokens
$contacts = (new MailtrapGeneralClient($config))->contacts($accountId);
$generalClient = new MailtrapGeneralClient($config);
$contacts = $generalClient->contacts($accountId);

/**
* A contact's subscription topic status is set per topic and domain: take the account's first
* topic, and the domain it covers (the first domain when the topic covers all of them).
* Accounts without Subscription Topics get 403 here, and the examples below leave topics out.
*
* GET https://mailtrap.io/api/subscription_topics
* GET https://mailtrap.io/api/accounts/{account_id}/domains
*/
$topicUnsubscription = null; // the contact unsubscribed from that topic on that domain
try {
$topic = ResponseHelper::toArray(
$generalClient->subscriptionTopics()->getSubscriptionTopics(perPage: 1)
)['data'][0] ?? null;

if ($topic !== null) {
$topicUnsubscription = ContactSubscriptionTopic::init(
$topic['id'],
$topic['domain_id'] ?? ResponseHelper::toArray(
(new MailtrapSendingClient($config))->domains($accountId)->getDomains()
)['data'][0]['id'],
ContactSubscriptionTopic::STATUS_UNSUBSCRIBED
);
}
} catch (Exception $e) {
echo 'Subscription topics are left out: ', $e->getMessage(), PHP_EOL;
}

/**
* Get contact
* With Subscription Topics, `data.subscription_topics` lists the contact's status per topic and
* domain; it is null when the statuses can't be read right now, and absent without topics.
*
* GET https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email}
*/
Expand Down Expand Up @@ -44,7 +76,8 @@
CreateContact::init(
'john.smith@example.com',
['first_name' => 'John', 'last_name' => 'Smith'], // Fields
[1, 2] // List IDs to which the contact will be added
[1, 2], // List IDs to which the contact will be added
$topicUnsubscription === null ? null : [$topicUnsubscription] // Subscription topic statuses (null leaves them out)
)
);

Expand Down Expand Up @@ -92,6 +125,37 @@
}


/**
* Update only a contact's subscription topic statuses: the topic and domain pairs left out keep
* their status. A 503 whose exception message names the contact means the contact was saved but
* its topic statuses were not: send them again to that contact. A 503 without it saved nothing.
*
* PATCH https://mailtrap.io/api/accounts/{account_id}/contacts/{id_or_email}
*/
try {
if ($topicUnsubscription !== null) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
$response = $contacts->updateContactByEmail(
'john.smith@example.com',
UpdateContact::init(
email: 'john.smith@example.com',
subscriptionTopics: [
ContactSubscriptionTopic::init(
$topicUnsubscription->getSubscriptionTopicId(),
$topicUnsubscription->getDomainId(),
ContactSubscriptionTopic::STATUS_SUBSCRIBED // resubscribe
),
]
)
);

// print the response body (array)
var_dump(ResponseHelper::toArray($response));
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), PHP_EOL;
}


/**
* Delete contact
*
Expand Down Expand Up @@ -125,7 +189,8 @@
email: 'customer1@example.com',
fields: ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111],
listIdsIncluded: [1, 2],
listIdsExcluded: [4, 5]
listIdsExcluded: [4, 5],
subscriptionTopics: $topicUnsubscription === null ? null : [$topicUnsubscription]
),
new ImportContact(
email: 'customer2@example.com',
Expand Down
37 changes: 34 additions & 3 deletions examples/email-campaigns/all.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
require __DIR__ . '/../../vendor/autoload.php';

$accountId = (int) $_ENV['MAILTRAP_ACCOUNT_ID'];
$domainId = (int) $_ENV['MAILTRAP_DOMAIN_ID']; // set this environment variable with your domain ID
$config = new Config($_ENV['MAILTRAP_API_KEY']); // your API token from https://mailtrap.io/api-tokens
$emailCampaigns = (new MailtrapGeneralClient($config))->emailCampaigns($accountId);
$generalClient = new MailtrapGeneralClient($config);
$emailCampaigns = $generalClient->emailCampaigns($accountId);

/**
* Get a paginated list of email campaigns (newest first).
Expand All @@ -33,16 +35,44 @@
echo 'Caught exception: ', $e->getMessage(), PHP_EOL;
}

/**
* Pick the subscription topic the campaign is sent for: the first one that covers the campaign's
* domain (a topic with no `domain_id` covers every domain). Accounts without Subscription Topics
* get 403 here, and the campaign below is created without a topic.
*
* GET https://mailtrap.io/api/subscription_topics
*/
$subscriptionTopicId = null;
try {
$subscriptionTopics = $generalClient->subscriptionTopics();
$token = null;
do {
$topics = ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 100, token: $token));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

foreach ($topics['data'] as $topic) {
if ($topic['domain_id'] === null || $topic['domain_id'] === $domainId) {
$subscriptionTopicId = $topic['id'];
break;
}
}

$token = $topics['pagination']['next_token'] ?? null; // the next page, null after the last one
} while ($subscriptionTopicId === null && $token !== null);
} catch (Exception $e) {
echo 'No subscription topic for the campaign: ', $e->getMessage(), PHP_EOL;
}

/**
* Create a new email campaign in the `draft` state (wrapped in `data`).
* `name`, `domain_id`, `from_local_part` and a template `subject` are required.
* `subscription_topic_id` is left out when null; the response returns it, null without a topic.
*
* POST https://mailtrap.io/api/email_campaigns
*/
try {
$response = $emailCampaigns->createEmailCampaign(new CreateEmailCampaign(
name: 'Spring Sale',
domainId: (int) $_ENV['MAILTRAP_DOMAIN_ID'], // set this environment variable with your domain ID
domainId: $domainId,
fromLocalPart: 'news',
templateAttributes: new TemplateAttributes(subject: 'Spring is here — 30% off'),
fromDisplayName: 'Acme Marketing',
Expand All @@ -51,6 +81,7 @@
localPart: 'support',
domain: 'acme.com',
),
subscriptionTopicId: $subscriptionTopicId,
));

$emailCampaign = ResponseHelper::toArray($response);
Expand Down Expand Up @@ -221,7 +252,7 @@
try {
$throwaway = ResponseHelper::toArray($emailCampaigns->createEmailCampaign(new CreateEmailCampaign(
name: 'Draft to delete',
domainId: (int) $_ENV['MAILTRAP_DOMAIN_ID'],
domainId: $domainId,
fromLocalPart: 'news',
templateAttributes: new TemplateAttributes(subject: 'Draft to delete')
)));
Expand Down
10 changes: 10 additions & 0 deletions examples/sending/email-logs.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,16 @@
echo "Status: " . $message['status'] . PHP_EOL;
echo "Subject: " . ($message['subject'] ?? '') . PHP_EOL;
echo "Events: " . count($message['events'] ?? []) . PHP_EOL;

// Each event's `details` depend on its `event_type`; the API may add types, so don't fail on
// one you don't know. The subscription topic events carry the topic's ID.
foreach ($message['events'] ?? [] as $event) {
$line = " - " . $event['event_type'] . " at " . $event['created_at'];
if (in_array($event['event_type'], ['topic_unsubscribe', 'topic_resubscribe'], true)) {
$line .= " (subscription topic " . ($event['details']['subscription_topic_id'] ?? 'unknown') . ")";
}
echo $line . PHP_EOL;
}
} else {
echo "No messages in the list." . PHP_EOL;
}
Expand Down
9 changes: 9 additions & 0 deletions examples/sending/suppressions.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@
)
);

// OR include contacts' subscription topic unsubscriptions: rows of type
// Suppression::TYPE_TOPIC_UNSUBSCRIPTION with their `subscription_topic_id`.
// Accounts without Subscription Topics have no such rows.
$response = $mailtrapSuppression->getSuppressions(
new SuppressionsFilter(includeTopicUnsubscriptions: true)
);

// Print the response body (array)
var_dump(ResponseHelper::toArray($response));
} catch (Exception $e) {
Expand Down Expand Up @@ -68,6 +75,8 @@

/**
* Delete Suppression by ID.
* Topic unsubscription rows can't be deleted (404): resubscribe the contact to the topic in a
* contact update instead (see contacts/all.php).
*
* DELETE https://mailtrap.io/api/accounts/{account_id}/suppressions/{suppression_id}
*/
Expand Down
60 changes: 60 additions & 0 deletions examples/subscription-topics/all.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php

declare(strict_types=1);

use Mailtrap\Config;
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapGeneralClient;

require __DIR__ . '/../../vendor/autoload.php';

$config = new Config($_ENV['MAILTRAP_API_KEY']); // your API token from https://mailtrap.io/api-tokens
$subscriptionTopics = (new MailtrapGeneralClient($config))->subscriptionTopics();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

/**
* Get a paginated list of subscription topics; deleted topics are left out.
* Optional: $perPage (max 100, default 50) and $token (page number).
*
* The response is wrapped in `{ data: [...], pagination }`. A topic's `domain_id` is null when
* it covers every domain of the account.
*
* GET https://mailtrap.io/api/subscription_topics
*/
try {
$topics = ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 50));

var_dump($topics);

// pass `pagination.next_token` with the same $perPage to get the next page
$nextToken = $topics['pagination']['next_token'] ?? null;
if ($nextToken !== null) {
var_dump(ResponseHelper::toArray($subscriptionTopics->getSubscriptionTopics(perPage: 50, token: $nextToken)));
}
} catch (Exception $e) {
echo $e->getCode() === 403
? 'Subscription Topics are not available for this account.'
: 'Caught exception: ' . $e->getMessage();
echo PHP_EOL;

exit(1);
}

/**
* Get a subscription topic by ID (wrapped in `data`). A deleted topic is returned too, with
* `deleted_at` set.
*
* GET https://mailtrap.io/api/subscription_topics/{subscription_topic_id}
*/
try {
$subscriptionTopicId = $topics['data'][0]['id'] ?? null;

if ($subscriptionTopicId !== null) {
$response = $subscriptionTopics->getSubscriptionTopic($subscriptionTopicId);

var_dump(ResponseHelper::toArray($response));
} else {
echo 'No subscription topics yet: create one in Mailtrap first.', PHP_EOL;
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), PHP_EOL;
}
25 changes: 25 additions & 0 deletions examples/webhooks/all.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,31 @@
echo 'Caught exception: ', $e->getMessage(), "\n";
}

/**
* Create a campaigns webhook that also reports subscription topic preference changes.
* Campaigns webhooks require `event_types` and take no sending stream.
* `subscription_preferences_update` is available on campaigns webhooks and Bulk stream
* email_sending webhooks only.
*
* POST https://mailtrap.io/api/accounts/{account_id}/webhooks
*/
try {
$response = $webhooks->createWebhook(new CreateWebhook(
url: 'https://example.com/mailtrap/campaign-webhooks',
webhookType: Webhook::TYPE_CAMPAIGNS,
eventTypes: [
Webhook::EVENT_DELIVERY,
Webhook::EVENT_UNSUBSCRIBE,
Webhook::EVENT_SUBSCRIPTION_PREFERENCES_UPDATE,
],
payloadFormat: Webhook::PAYLOAD_FORMAT_JSON,
));

var_dump(ResponseHelper::toArray($response));
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}

/**
* Update an existing webhook.
* Only `url`, `active`, `payload_format`, and `event_types` are mutable.
Expand Down
5 changes: 1 addition & 4 deletions src/Api/AbstractApi.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,7 @@ protected function handleResponse(ResponseInterface $response): ResponseInterfac
case $statusCode >= 400 && $statusCode < 500:
throw HttpClientException::createFromResponse($response);
case $statusCode >= 500:
throw new HttpServerException(
sprintf('Internal Server Error. HTTP response code ("%d") received from the API server. Retry later or contact support.', $statusCode),
$statusCode
);
throw HttpServerException::createFromResponse($response);
default:
throw new HttpException(
sprintf('An unexpected error occurred. HTTP response code ("%d") received.', $statusCode),
Expand Down
7 changes: 7 additions & 0 deletions src/Api/General/Contact.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,13 @@

/**
* Class Contact
*
* With Subscription Topics, a contact's get, create and update responses carry
* `data.subscription_topics`: its status per topic and domain, null when the statuses can't be
* read (retry later), and absent for an account without topics. A create or update with
* subscription topics that fails with a `503` whose HttpServerException message names the contact
* saved the contact but not its topic statuses: send them again to that contact, in an update. A
* `503` without that message (from a proxy or during a deploy, say) saved nothing.
*/
class Contact extends AbstractApi implements GeneralInterface
{
Expand Down
Loading
Loading