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 @@ -393,6 +393,7 @@ You can find the [Mailtrap Java API reference](https://mailtrap.github.io/mailtr

- [Email Campaigns](examples/java/io/mailtrap/examples/emailcampaigns/EmailCampaignsExample.java)
- [Marketing Stats](examples/java/io/mailtrap/examples/marketingstats/MarketingStatsExample.java)
- [Subscription Topics](examples/java/io/mailtrap/examples/subscriptiontopics/SubscriptionTopicsExample.java)

### Renamed APIs

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
package io.mailtrap.examples.contactimports;

import io.mailtrap.client.MailtrapClient;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.exception.http.HttpClientException;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.contactimports.Contact;
import io.mailtrap.model.request.contactimports.ImportContactsRequest;
import io.mailtrap.model.request.contacts.ContactSubscriptionTopic;
import io.mailtrap.model.response.contacts.ContactStatus;
import io.mailtrap.model.response.sendingdomains.SendingDomainsResponse;
import io.mailtrap.model.response.subscriptiontopics.SubscriptionTopic;

import java.util.List;
import java.util.Map;
import java.util.Optional;

public class ContactImportsExample {

Expand All @@ -23,8 +30,15 @@ public static void main(String[] args) {

final var client = MailtrapClientFactory.createMailtrapClient(config);

final var importRequest = new ImportContactsRequest(
List.of(new Contact(EMAIL, Map.of("first_name", "Nick"), List.of(LIST_1_ID), List.of(LIST_2_ID))));
// With subscription topics, each contact can carry its topic preferences, one entry per topic and sending
// domain. An account without them rejects the import, so they are sent only when there is a topic.
final var importRequest = new ImportContactsRequest(List.of(Contact.builder()
.email(EMAIL)
.fields(Map.of("first_name", "Nick"))
.listIdsIncluded(List.of(LIST_1_ID))
.listIdsExcluded(List.of(LIST_2_ID))
.subscriptionTopics(firstTopicPreference(client, ContactStatus.UNSUBSCRIBED).map(List::of).orElse(null))
.build()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

final var createResponse = client.contactsApi().contactImports()
.importContacts(ACCOUNT_ID, importRequest);
Expand All @@ -36,4 +50,34 @@ public static void main(String[] args) {

System.out.println(contactImportResponse);
}

/**
* The first subscription topic, as an entry on its sending domain or on the account's first one; empty for an
* account without subscription topics.
*/
private static Optional<ContactSubscriptionTopic> firstTopicPreference(final MailtrapClient client,
final ContactStatus status) {
final List<SubscriptionTopic> topics;
try {
topics = client.marketingApi().subscriptionTopics().getSubscriptionTopics(null).getData();
} catch (final HttpClientException e) {
System.out.println("Subscription topics aren't available for this account: " + e.getMessage());
return Optional.empty();
}
if (topics.isEmpty()) {
return Optional.empty();
}

final var topic = topics.get(0);
// A topic without a domain covers every sending domain, and an entry names one of them.
final Optional<Long> domainId = topic.getDomainId() != null
? Optional.of(topic.getDomainId())
: client.sendingApi().domains().getDomains(ACCOUNT_ID).stream().findFirst().map(SendingDomainsResponse::getId);

return domainId.map(id -> ContactSubscriptionTopic.builder()
.subscriptionTopicId(topic.getId())
.domainId(id)
.status(status)
.build());
}
}
48 changes: 48 additions & 0 deletions examples/java/io/mailtrap/examples/contacts/ContactsExample.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
package io.mailtrap.examples.contacts;

import io.mailtrap.client.MailtrapClient;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.exception.http.HttpClientException;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.request.contacts.ContactSubscriptionTopic;
import io.mailtrap.model.request.contacts.CreateContact;
import io.mailtrap.model.request.contacts.CreateContactRequest;
import io.mailtrap.model.request.contacts.UpdateContact;
import io.mailtrap.model.request.contacts.UpdateContactRequest;
import io.mailtrap.model.response.contacts.ContactStatus;
import io.mailtrap.model.response.sendingdomains.SendingDomainsResponse;
import io.mailtrap.model.response.subscriptiontopics.SubscriptionTopic;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class ContactsExample {

Expand Down Expand Up @@ -49,6 +56,47 @@ public static void main(String[] args) {

System.out.println(updateResponse);

// Unsubscribe the contact from one subscription topic on one sending domain. Entries left out keep their
// status, and the builder leaves unsubscribed out, so the contact stays subscribed to everything else.
firstTopicPreference(client, ContactStatus.UNSUBSCRIBED).ifPresent(preference -> {
final var topicsUpdateRequest = new UpdateContactRequest(
UpdateContact.builder().subscriptionTopics(List.of(preference)).build());

// null when the account has no subscription topics, or when they couldn't be read
System.out.println(client.contactsApi().contacts()
.updateContact(ACCOUNT_ID, EMAIL, topicsUpdateRequest).getData().getSubscriptionTopics());
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

client.contactsApi().contacts().deleteContact(ACCOUNT_ID, EMAIL);
}

/**
* The first subscription topic, as an entry on its sending domain or on the account's first one; empty for an
* account without subscription topics.
*/
private static Optional<ContactSubscriptionTopic> firstTopicPreference(final MailtrapClient client,
final ContactStatus status) {
final List<SubscriptionTopic> topics;
try {
topics = client.marketingApi().subscriptionTopics().getSubscriptionTopics(null).getData();
} catch (final HttpClientException e) {
System.out.println("Subscription topics aren't available for this account: " + e.getMessage());
return Optional.empty();
}
if (topics.isEmpty()) {
return Optional.empty();
}

final var topic = topics.get(0);
// A topic without a domain covers every sending domain, and an entry names one of them.
final Optional<Long> domainId = topic.getDomainId() != null
? Optional.of(topic.getDomainId())
: client.sendingApi().domains().getDomains(ACCOUNT_ID).stream().findFirst().map(SendingDomainsResponse::getId);

return domainId.map(id -> ContactSubscriptionTopic.builder()
.subscriptionTopicId(topic.getId())
.domainId(id)
.status(status)
.build());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

import io.mailtrap.api.emailcampaigns.EmailCampaignListFilter;
import io.mailtrap.api.emailcampaigns.EmailCampaignStatsFilter;
import io.mailtrap.api.subscriptiontopics.SubscriptionTopicListFilter;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.exception.http.HttpClientException;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.DeliveryMode;
import io.mailtrap.model.request.emailcampaigns.CreateEmailCampaign;
Expand All @@ -11,6 +13,7 @@
import io.mailtrap.model.request.emailcampaigns.UpdateEmailCampaign;
import io.mailtrap.model.response.emailcampaigns.DeliveryOptions;
import io.mailtrap.model.response.emailcampaigns.ReplyTo;
import io.mailtrap.model.response.subscriptiontopics.SubscriptionTopic;

import java.time.LocalDate;
import java.time.OffsetDateTime;
Expand Down Expand Up @@ -43,6 +46,26 @@ public static void main(String[] args) {
.build());
System.out.println(page);

// With subscription topics, a campaign is sent for a topic that covers its domain: here the first such
// topic, looked up page by page. Accounts without topics answer 403, and a campaign there has none.
Long subscriptionTopicId = null;
try {
final var subscriptionTopics = client.marketingApi().subscriptionTopics();
Integer topicsToken = null;
do {
final var topicsPage = subscriptionTopics.getSubscriptionTopics(
SubscriptionTopicListFilter.builder().perPage(100).token(topicsToken).build());
subscriptionTopicId = topicsPage.getData().stream()
.filter(topic -> topic.getDomainId() == null || topic.getDomainId() == DOMAIN_ID)
.findFirst()
.map(SubscriptionTopic::getId)
.orElse(null);
topicsToken = topicsPage.getPagination().getNextToken();
} while (subscriptionTopicId == null && topicsToken != null);
} catch (final HttpClientException e) {
System.out.println("Subscription topics aren't available for this account: " + e.getMessage());
}

// Create a campaign — it starts in the `draft` state. The request body is flat.
final var created = campaigns.createEmailCampaign(
CreateEmailCampaign.builder()
Expand All @@ -59,6 +82,8 @@ public static void main(String[] args) {
.subject("Spring is here — 30% off")
.build())
.contactListIds(List.of(CONTACT_LIST_ID))
// left out when null; an update can change the topic but not drop it
.subscriptionTopicId(subscriptionTopicId)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
.build());
System.out.println(created.getData());

Expand Down
17 changes: 17 additions & 0 deletions examples/java/io/mailtrap/examples/emaillogs/EmailLogsExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
import io.mailtrap.model.request.emaillogs.FilterExactString;
import io.mailtrap.model.request.emaillogs.FilterStatus;
import io.mailtrap.model.request.emaillogs.FilterOptionalString;
import io.mailtrap.model.response.emaillogs.EmailLogMessageEventTopicResubscribe;
import io.mailtrap.model.response.emaillogs.EmailLogMessageEventTopicUnsubscribe;
import io.mailtrap.model.response.emaillogs.EmailLogMessageEventUnknown;
import io.mailtrap.model.response.emaillogs.MessageStatus;

import java.time.Instant;
Expand Down Expand Up @@ -51,6 +54,20 @@ public static void main(String[] args) {
final var message = client.sendingApi().emailLogs().get(ACCOUNT_ID, messageId);
System.out.println(
"Message: " + message.getSubject() + " events: " + message.getEvents().size());

// Topic events carry the subscription topic's id. An event type this SDK version doesn't know reads as
// EmailLogMessageEventUnknown, with its raw type and details.
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
for (final var event : message.getEvents()) {
if (event instanceof EmailLogMessageEventTopicUnsubscribe unsubscribe) {
System.out.println(" unsubscribed from topic " + unsubscribe.getDetails().getSubscriptionTopicId());
} else if (event instanceof EmailLogMessageEventTopicResubscribe resubscribe) {
System.out.println(" resubscribed to topic " + resubscribe.getDetails().getSubscriptionTopicId());
} else if (event instanceof EmailLogMessageEventUnknown unknown) {
System.out.println(" " + unknown.getRawEventType() + ": " + unknown.getDetails());
} else {
System.out.println(" " + event.getEventType());
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package io.mailtrap.examples.subscriptiontopics;

import io.mailtrap.api.subscriptiontopics.SubscriptionTopicListFilter;
import io.mailtrap.config.MailtrapConfig;
import io.mailtrap.exception.http.HttpClientException;
import io.mailtrap.factory.MailtrapClientFactory;
import io.mailtrap.model.response.subscriptiontopics.SubscriptionTopicListResponse;

public class SubscriptionTopicsExample {

private static final String TOKEN = System.getenv("MAILTRAP_API_KEY");

public static void main(String[] args) {
final var config = new MailtrapConfig.Builder()
.token(TOKEN)
.build();

final var client = MailtrapClientFactory.createMailtrapClient(config);

// The subscription topic endpoints are token-scoped: the account is resolved from the API token.
// They are read-only: topics are created and edited in the Mailtrap app.
final var subscriptionTopics = client.marketingApi().subscriptionTopics();
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

final SubscriptionTopicListResponse page;
try {
// Topics by id, deleted ones left out. Pass null for the first page with API defaults.
page = subscriptionTopics.getSubscriptionTopics(SubscriptionTopicListFilter.builder().perPage(50).build());
} catch (final HttpClientException e) {
if (e.getStatusCode() == 403) {
System.out.println("Subscription topics aren't available for this account or token");
return;
}
throw e;
}

// A topic with a null domainId covers every sending domain.
page.getData().forEach(System.out::println);

// Pass the next token with the same perPage to get the next page.
if (page.getPagination().getNextToken() != null) {
System.out.println(subscriptionTopics.getSubscriptionTopics(SubscriptionTopicListFilter.builder()
.perPage(50)
.token(page.getPagination().getNextToken())
.build()).getData());
}

if (page.getData().isEmpty()) {
System.out.println("The account has no subscription topics yet");
return;
}

// Get one topic by id. This also returns a topic deleted after a campaign was assigned it, with deletedAt set.
System.out.println(subscriptionTopics.getSubscriptionTopic(page.getData().get(0).getId()).getData());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,17 @@ public static void main(String[] args) {
.build()
));

// Also list the contacts' subscription topic unsubscriptions, with type TOPIC_UNSUBSCRIPTION and their
// subscriptionTopicId. Those rows can't be deleted here: a contact update resubscribes to a topic.
System.out.println(suppressions.search(
ACCOUNT_ID,
SuppressionListFilter.builder()
.email(EMAIL)
.includeTopicUnsubscriptions(true)
.build()
));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// The default list has no topic unsubscriptions, so its first row can be deleted.
if (!searchResponse.isEmpty()) {
final var deletedSuppression = suppressions
.deleteSuppression(ACCOUNT_ID, searchResponse.get(0).getId());
Expand Down
13 changes: 13 additions & 0 deletions examples/java/io/mailtrap/examples/webhooks/WebhooksExample.java
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,18 @@ public static void main(String[] args) {

final var deleteResponse = client.generalApi().webhooks().deleteWebhook(ACCOUNT_ID, webhookId);
System.out.println(deleteResponse);

// Subscription preference updates go to Bulk email-sending and Campaigns webhooks only; the API rejects
// them on a transactional webhook.
final var campaignsWebhook = client.generalApi().webhooks().createWebhook(ACCOUNT_ID, new CreateWebhookRequest(
WebhookInput.builder()
.url(WEBHOOK_URL)
.webhookType(WebhookType.CAMPAIGNS)
.payloadFormat(WebhookPayloadFormat.JSON)
.eventTypes(List.of(WebhookEventType.DELIVERY, WebhookEventType.SUBSCRIPTION_PREFERENCES_UPDATE))
.build()));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
System.out.println(campaignsWebhook);

client.generalApi().webhooks().deleteWebhook(ACCOUNT_ID, campaignsWebhook.getData().getId());
}
}
3 changes: 3 additions & 0 deletions src/main/java/io/mailtrap/Mapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public class Mapper {
private static final ObjectMapper mapper = JsonMapper.builder()
.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
// An enum value a newer API sends reads as null instead of failing the response: every fromValue throws
// IllegalArgumentException for an unknown value, which this turns into null
.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)
.serializationInclusion(JsonInclude.Include.NON_EMPTY)
.addModule(new SimpleModule().addDeserializer(ErrorResponse.class, new ErrorResponseDeserializer()))
.addModule(new JavaTimeModule())
Expand Down
5 changes: 5 additions & 0 deletions src/main/java/io/mailtrap/api/contacts/Contacts.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ public interface Contacts {
* @param accountId unique account ID
* @param request required contact data
* @return created contact
* @throws io.mailtrap.exception.http.HttpServerException of status {@code 503} when the contact was saved but its
* subscription topic preferences were not: send them again in an update of the contact its message names
*/
CreateContactResponse createContact(long accountId, CreateContactRequest request);

Expand All @@ -40,6 +42,9 @@ public interface Contacts {
* @param accountId unique account ID
* @param idOrEmail contact ID or Email
* @param request request body
* @return updated contact
* @throws io.mailtrap.exception.http.HttpServerException of status {@code 503} when the contact was saved but its
* subscription topic preferences were not: send them again in an update of the contact its message names
*/
UpdateContactResponse updateContact(long accountId, String idOrEmail,
UpdateContactRequest request);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package io.mailtrap.api.subscriptiontopics;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
* Pagination parameters for listing subscription topics. All fields are optional;
* {@code null} fields are omitted from the query string.
*/
@Data
@NoArgsConstructor
@AllArgsConstructor

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Non-blocking. In bade5c8 you made the all-args constructors private so that adding a field doesn't break callers' constructor signatures. This new class has a public @AllArgsConstructor, so the next field added here will hit the same problem. It matches EmailCampaignListFilter and TemplateListFilter, so consistency is a fair reason to keep it. Since the class is new and has no callers yet, though, @AllArgsConstructor(access = AccessLevel.PRIVATE) costs nothing now.

@Builder
public class SubscriptionTopicListFilter {

/**
* Number of topics per page (max 100, default 50).
*/
private Integer perPage;

/**
* Page number to retrieve (page-token pagination, default 1).
*/
private Integer token;
}
Loading
Loading