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 @@ -273,6 +273,7 @@ Contact management:
Email Marketing:

- Email campaigns CRUD, lifecycle & stats – [`email-campaigns/everything.ts`](examples/email-campaigns/everything.ts)
- Subscription topics (list & get) – [`subscription-topics/everything.ts`](examples/subscription-topics/everything.ts)
- Email Marketing stats (campaigns and automations, aggregated) – [`marketing-stats/everything.ts`](examples/marketing-stats/everything.ts)

General API:
Expand Down
36 changes: 35 additions & 1 deletion examples/contact-imports/everything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,45 @@ const client = new MailtrapClient({
accountId: ACCOUNT_ID
});

// An account without subscription topics answers `403` with an empty body.
const isForbidden = (error: unknown) =>
(error as { cause?: { response?: { status?: number } } }).cause?.response
?.status === 403;

// A preference for the account's first subscription topic, on the topic's
// domain or, for an "All domains" topic, on the account's first domain.
// Returns `undefined` on an account without subscription topics.
async function findTopicPreference() {
try {
const topics = await client.subscriptionTopics.getList({ per_page: 1 });
const topic = topics.data[0];
if (!topic) return undefined;

const domainId =
topic.domain_id ?? (await client.domains.getList()).data[0]?.id;
if (domainId === undefined) return undefined;

return {
subscription_topic_id: topic.id,
domain_id: domainId,
status: "unsubscribed" as const,
};
} catch (error) {
if (isForbidden(error)) return undefined;
throw error;
}
}

async function runContactImportsFlow() {
// A contact's `subscription_topics` sets its status for each topic and
// domain pair given; an import that sends them fails on an account without
// subscription topics.
const topicPreference = await findTopicPreference();
const importData = {
contacts: [
{
email: "customer1@example.com"
email: "customer1@example.com",
...(topicPreference && { subscription_topics: [topicPreference] })
},
{
email: "customer2@example.com"
Expand Down
45 changes: 45 additions & 0 deletions examples/contacts/everything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,35 @@ const client = new MailtrapClient({
accountId: ACCOUNT_ID
});

// An account without subscription topics answers `403` with an empty body.
const isForbidden = (error: unknown) =>
(error as { cause?: { response?: { status?: number } } }).cause?.response
?.status === 403;

// A preference for the account's first subscription topic, on the topic's
// domain or, for an "All domains" topic, on the account's first domain.
// Returns `undefined` on an account without subscription topics.
async function findTopicPreference() {
try {
const topics = await client.subscriptionTopics.getList({ per_page: 1 });
const topic = topics.data[0];
if (!topic) return undefined;

const domainId =
topic.domain_id ?? (await client.domains.getList()).data[0]?.id;
if (domainId === undefined) return undefined;

return {
subscription_topic_id: topic.id,
domain_id: domainId,
status: "unsubscribed" as const,
};
} catch (error) {
if (isForbidden(error)) return undefined;
throw error;
}
}

const contactData = {
email: "john.smith@example.com",
fields: {
Expand Down Expand Up @@ -38,6 +67,22 @@ client.contacts
})
console.log("Contact updated:", updateResponse.data);

// Unsubscribe the contact from one subscription topic on one domain. The
// topic and domain pairs left out keep their status. Contact responses
// list every pair in `subscription_topics`: it is absent on an account
// without subscription topics, and `null` when they couldn't be read.
const topicPreference = await findTopicPreference();
if (topicPreference) {
const topicsResponse = await client.contacts.update(contactId, {
email: contactData.email,
subscription_topics: [topicPreference],
});
console.log(
"Contact subscription topics:",
topicsResponse.data.subscription_topics
);
}

// Delete contact
await client.contacts.delete(contactId);
console.log("Contact deleted");
Expand Down
39 changes: 38 additions & 1 deletion examples/email-campaigns/everything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,35 @@ const SENDING_DOMAIN_ID = "<YOUR-SENDING-DOMAIN-ID-HERE>";
// The Email Campaigns API is token-scoped — no `accountId` is needed.
const client = new MailtrapClient({ token: TOKEN });

// An account without subscription topics answers `403` with an empty body.
const isForbidden = (error: unknown) =>
(error as { cause?: { response?: { status?: number } } }).cause?.response
?.status === 403;

// A campaign's subscription topic must cover its domain: an "All domains"
// topic (`domain_id: null`) or one of that domain. Returns `undefined` when
// the account has no such topic, or no subscription topics at all.
async function findSubscriptionTopicId(domainId: number) {
try {
let token: number | null = 1;
while (token !== null) {
const page = await client.subscriptionTopics.getList({
per_page: 100,
token,
});
const topic = page.data.find(
({ domain_id }) => domain_id === null || domain_id === domainId
);
if (topic) return topic.id;
token = page.pagination.next_token;
}
return undefined;
} catch (error) {
if (isForbidden(error)) return undefined;
throw error;
}
}

async function emailCampaignsFlow() {
try {
const scheduledAt = new Date(Date.now() + 60 * 60 * 1000).toISOString();
Expand All @@ -22,8 +51,13 @@ async function emailCampaignsFlow() {
console.log("Campaigns:", JSON.stringify(list.data, null, 2));
console.log("Pagination:", JSON.stringify(list.pagination, null, 2));

const subscriptionTopicId = await findSubscriptionTopicId(
Number(SENDING_DOMAIN_ID)
);

// Create a campaign. It starts in the `draft` state. Single-campaign
// responses are wrapped in a `{ data }` envelope.
// responses are wrapped in a `{ data }` envelope. `subscription_topic_id`
// is optional; leave it out rather than sending `null`.
const created = await client.emailCampaigns.create({
name: "Spring Sale",
domain_id: Number(SENDING_DOMAIN_ID),
Expand All @@ -35,6 +69,9 @@ async function emailCampaignsFlow() {
domain: "acme.com",
},
template_attributes: { subject: "Spring is here — 30% off" },
...(subscriptionTopicId !== undefined && {
subscription_topic_id: subscriptionTopicId,
}),
});
console.log("Created campaign:", JSON.stringify(created.data, null, 2));

Expand Down
8 changes: 8 additions & 0 deletions examples/email-logs/everything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ async function emailLogsFlow() {
const messageId = list.messages[0].message_id;
const message = await client.emailLogs.get(messageId);
console.log("Single message:", message.subject, "events:", message.events?.length ?? 0);

// Narrow events by `event_type`. A recipient's unsubscribe from, or
// resubscribe to, one subscription topic names the topic.
for (const event of message.events ?? []) {
if (event.event_type === "topic_unsubscribe" || event.event_type === "topic_resubscribe") {
console.log(event.event_type, "topic:", event.details.subscription_topic_id);
}
}
}
} catch (error) {
console.error("Error in emailLogsFlow:", error instanceof Error ? error.message : String(error));
Expand Down
15 changes: 14 additions & 1 deletion examples/sending/suppressions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ async function suppressionsFlow() {
const filteredSuppressions = await client.suppressions.getList({email: "test@example.com"});
console.log("Filtered suppressions:", filteredSuppressions);

// Include contacts' unsubscriptions from single subscription topics, as
// "topic unsubscription" rows with their `subscription_topic_id`. Needs a
// token that can read contacts; without subscription topics there are none.
const withTopics = await client.suppressions.getList({
include_topic_unsubscriptions: true
});
console.log(
"Topic unsubscriptions:",
withTopics.filter((suppression) => suppression.type === "topic unsubscription")
);

// Add an email to the suppression list. `type` defaults to "manual import".
const created = await client.suppressions.create({
email: "suppressed@example.com",
Expand All @@ -25,7 +36,9 @@ async function suppressionsFlow() {
});
console.log("Created suppression:", created.data);

// Delete a suppression by ID (if any exist)
// Delete a suppression by ID (if any exist). The list without
// `include_topic_unsubscriptions` has no topic unsubscriptions, which can't
// be deleted.
if (suppressions.length > 0) {
const suppressionToDelete = suppressions[0];
await client.suppressions.delete(suppressionToDelete.id);
Expand Down
52 changes: 52 additions & 0 deletions examples/subscription-topics/everything.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { MailtrapClient } from "mailtrap";

const TOKEN = "<YOUR-TOKEN-HERE>";

// The Subscription Topics API is token-scoped — no `accountId` is needed.
const client = new MailtrapClient({ token: TOKEN });
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// An account without subscription topics answers `403` with an empty body.
const isForbidden = (error: unknown) =>
(error as { cause?: { response?: { status?: number } } }).cause?.response
?.status === 403;

async function subscriptionTopicsFlow() {
try {
// List every topic, one page at a time (page-token pagination). The list
// leaves out deleted topics. A `domain_id` of `null` means the topic
// covers every domain.
const topics = [];
let token: number | null = 1;
while (token !== null) {
const page = await client.subscriptionTopics.getList({
per_page: 100,
token,
});
topics.push(...page.data);
token = page.pagination.next_token;
}
console.log("Subscription topics:", JSON.stringify(topics, null, 2));

if (topics.length === 0) {
console.log("No subscription topics found for this account.");
return;
}

// Get one topic by ID. `get` also returns a deleted topic, with
// `deleted_at` set.
const topic = await client.subscriptionTopics.get(topics[0].id);
console.log("One topic:", JSON.stringify(topic.data, null, 2));
} catch (error) {
if (isForbidden(error)) {
console.error("Subscription topics are not available for this account.");
return;
}

console.error(
"Error in subscriptionTopicsFlow:",
error instanceof Error ? error.message : String(error)
);
}
}

subscriptionTopicsFlow();
10 changes: 10 additions & 0 deletions examples/webhooks/everything.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,16 @@ async function webhooksFlow() {
// Delete the webhook
const deleted = await client.webhooks.delete(webhookId);
console.log("Deleted webhook:", JSON.stringify(deleted, null, 2));

// Campaigns webhooks, and email-sending webhooks on the bulk stream, can
// also report a contact's subscription topic preference changes.
const campaignsWebhook = await client.webhooks.create({
url: "https://example.com/webhooks/mailtrap/campaigns",
webhook_type: "campaigns",
event_types: ["unsubscribe", "subscription_preferences_update"],
});
console.log("Created campaigns webhook:", JSON.stringify(campaignsWebhook, null, 2));
await client.webhooks.delete(campaignsWebhook.data.id);
} catch (error) {
console.error("Error in webhooksFlow:", error instanceof Error ? error.message : String(error));
}
Expand Down
16 changes: 16 additions & 0 deletions src/__tests__/lib/api/SubscriptionTopics.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import axios from "axios";

import SubscriptionTopicsBaseAPI from "../../../lib/api/SubscriptionTopics";

describe("lib/api/SubscriptionTopics: ", () => {
const subscriptionTopicsAPI = new SubscriptionTopicsBaseAPI(axios);

describe("class SubscriptionTopicsBaseAPI(): ", () => {
describe("init: ", () => {
it("initializes with all necessary params.", () => {
expect(subscriptionTopicsAPI).toHaveProperty("getList");
expect(subscriptionTopicsAPI).toHaveProperty("get");
});
});
});
});
27 changes: 27 additions & 0 deletions src/__tests__/lib/api/resources/ContactImports.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,33 @@ describe("lib/api/resources/ContactImports: ", () => {
expect(result).toEqual(expectedResponseData);
});

it("sends each contact's subscription topics.", async () => {
const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/imports`;
const topicsRequest: ImportContactsRequest = {
contacts: [
{
email: "customer1@example.com",
subscription_topics: [
{
subscription_topic_id: 12,
domain_id: 4321,
status: "unsubscribed",
},
],
},
{ email: "customer2@example.com" },
],
};

expect.assertions(2);

mock.onPost(endpoint, topicsRequest).reply(200, createImportResponse);
const result = await contactImportsAPI.create(topicsRequest);

expect(JSON.parse(mock.history.post[0].data)).toEqual(topicsRequest);
expect(result).toEqual(createImportResponse);
});

it("fails with error.", async () => {
const endpoint = `${GENERAL_ENDPOINT}/api/accounts/${accountId}/contacts/imports`;
const expectedErrorMessage = "Request failed with status code 400";
Expand Down
Loading