Skip to content

MT-22401: Add Email Campaigns API - #65

Open
Rabsztok wants to merge 1 commit into
mainfrom
MT-22401-java-email-campaigns
Open

MT-22401: Add Email Campaigns API#65
Rabsztok wants to merge 1 commit into
mainfrom
MT-22401-java-email-campaigns

Conversation

@Rabsztok

@Rabsztok Rabsztok commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

Motivation

https://railsware.atlassian.net/browse/MT-22401

Port the Email Campaigns public API (MT-21113) to the Java SDK.

Changes

  • Add client.emailCampaignsApi().emailCampaigns() covering the full contract: list (per_page/search/token), get, create, update, delete (204 → void), the five lifecycle actions (start, schedule, cancel, terminate, reset), and stats with an optional date window
  • Models follow the published OpenAPI schema: flat request bodies (wrapper classes removed), data-envelope response types, UUID mailsendDomainId, RAPID/GRADUAL delivery modes, 10-value CampaignState, audience id lists, TemplateAttributes with bodyHtml/bodyText/mergeTags, per-recipient state-metadata errors
  • ScheduleEmailCampaignRequest serializes datetime as ISO 8601 (@JsonFormat(shape = STRING)) — the default mapper would emit numeric timestamps
  • Full-lifecycle example + README "Email Marketing API" section

How to test

  • Run EmailCampaignsExample with a real API token and a verified sending domain — create a draft, update design/audience, schedule + cancel, fetch stats, delete
  • Verify a campaign in each lifecycle state deserializes (CampaignState is fail-closed on unknown values)

Summary by CodeRabbit

  • New Features
    • Added Email Campaigns API support.
    • Create, list, retrieve, update, delete, start, schedule, cancel, terminate, and reset campaigns.
    • Retrieve campaign performance statistics, including optional date filtering.
    • Configure campaign templates, recipients, sender details, and rapid or gradual delivery.
  • Documentation
    • Added a Java Email Campaigns example and linked it from the usage guide.
  • Tests
    • Added comprehensive coverage and sample responses for campaign operations and lifecycle states.

Decisions:
- Request bodies are flat per the current contract — the email_campaign wrapper classes were deleted; CreateEmailCampaign/UpdateEmailCampaign extend AbstractModel and are passed directly
- Single-object and stats responses unwrap through data-envelope types (EmailCampaignResponse, EmailCampaignStatsResponse), following the GetContactResponse precedent
- deleteEmailCampaign returns void via Void.class since the API responds 204 No Content
- Five lifecycle endpoints (start/schedule/cancel/terminate/reset) share a no-body POST helper; ScheduleEmailCampaignRequest.datetime is OffsetDateTime with @jsonformat(shape = STRING) because the mapper otherwise emits numeric timestamps
- CampaignState carries the full 10-value enum — its @JsonCreator throws on unknown values, so stale values hard-fail against production
@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a token-scoped Email Campaigns API with campaign models, CRUD and lifecycle operations, statistics retrieval, client-factory integration, mocked tests with JSON fixtures, and an end-to-end Java example linked from the README.

Changes

Email Campaigns API

Layer / File(s) Summary
Campaign contracts and data models
src/main/java/io/mailtrap/model/..., src/main/java/io/mailtrap/api/emailcampaigns/EmailCampaigns.java
Defines campaign request/response models, lifecycle states, delivery settings, templates, pagination, statistics, and the public API contract.
Campaign REST operations
src/main/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImpl.java
Implements listing, creation, retrieval, updates, deletion, lifecycle actions, scheduling, and statistics requests.
Client factory integration
src/main/java/io/mailtrap/client/..., src/main/java/io/mailtrap/factory/MailtrapClientFactory.java
Exposes the email campaigns API through MailtrapClient and wires it through the factory.
API tests and response fixtures
src/test/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImplTest.java, src/test/resources/api/emailcampaigns/*
Tests campaign operations and validates campaign, lifecycle, pagination, scheduling, and statistics payloads.
Campaign usage example
examples/java/io/mailtrap/examples/emailcampaigns/EmailCampaignsExample.java, README.md
Demonstrates the complete campaign workflow and adds it to the README API reference.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MailtrapClient
  participant MailtrapEmailCampaignsApi
  participant EmailCampaignsImpl
  participant EmailCampaignsAPI
  MailtrapClient->>MailtrapEmailCampaignsApi: access email campaigns endpoint
  MailtrapEmailCampaignsApi->>EmailCampaignsImpl: invoke campaign operation
  EmailCampaignsImpl->>EmailCampaignsAPI: send campaign request
  EmailCampaignsAPI-->>EmailCampaignsImpl: return campaign or statistics response
  EmailCampaignsImpl-->>MailtrapEmailCampaignsApi: deserialize response model
Loading

Suggested reviewers: mklocek, igordobryn, vittorius

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: adding the Email Campaigns API.
Description check ✅ Passed The description covers Motivation, Changes, and How to test with enough detail; only the Images and GIFs section is missing.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Rabsztok
Rabsztok marked this pull request as ready for review July 30, 2026 12:03
@Rabsztok
Rabsztok requested review from IgorDobryn and mklocek July 30, 2026 12:12

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/test/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImplTest.java (1)

97-132: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover per_page and token request serialization.

The suite asserts pagination fields from the response but never calls getEmailCampaigns with perPage or token. Add a matching DataMock and test invocation so query-key/type regressions are caught.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/test/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImplTest.java`
around lines 97 - 132, Add a dedicated getEmailCampaigns test using a matching
DataMock response and invoke api.getEmailCampaigns with non-null perPage and
token values. Assert the existing response expectations while ensuring the
request serialization covers both pagination query keys and their numeric types.
src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java (1)

1-71: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

CreateEmailCampaign and UpdateEmailCampaign are structurally duplicated and both depend on the response package for shared types.

Both classes declare an identical set of fields (name, mailsendDomainId, fromDisplayName, fromLocalPart, replyTo, templateAttributes, deliveryMode, deliveryOptions, contactListIds, contactSegmentIds) with the same annotations, and both import ReplyTo/DeliveryOptions from io.mailtrap.model.response.emailcampaigns for request bodies. This is a DRY violation and a layering smell (request DTOs depending on the response package for types that are genuinely shared).

  • src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java#L1-L71: extract the common fields into a shared abstract base (e.g. AbstractEmailCampaignRequest) that both CreateEmailCampaign and UpdateEmailCampaign extend, and move ReplyTo/DeliveryOptions to a neutral shared package (e.g. io.mailtrap.model.emailcampaigns) instead of response.emailcampaigns.
  • src/main/java/io/mailtrap/model/request/emailcampaigns/UpdateEmailCampaign.java#L1-L70: extend the same shared base class once introduced, removing the duplicated field declarations.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java`
around lines 1 - 71, The email campaign request DTOs duplicate fields and depend
on response-only shared types. Create an AbstractEmailCampaignRequest containing
the common fields and annotations, make CreateEmailCampaign and
UpdateEmailCampaign extend it, and remove their duplicated declarations; move
ReplyTo and DeliveryOptions from io.mailtrap.model.response.emailcampaigns to a
neutral shared package and update both request DTOs and other references. Apply
the changes in
src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java#L1-L71
and
src/main/java/io/mailtrap/model/request/emailcampaigns/UpdateEmailCampaign.java#L1-L70.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@examples/java/io/mailtrap/examples/emailcampaigns/EmailCampaignsExample.java`:
- Around line 81-82: Update the timestamp passed to
EmailCampaignsExample.scheduleEmailCampaign so it is always future-dated when
the example runs, preferably by deriving it from the current time; preserve the
existing UTC OffsetDateTime request construction.

---

Nitpick comments:
In
`@src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java`:
- Around line 1-71: The email campaign request DTOs duplicate fields and depend
on response-only shared types. Create an AbstractEmailCampaignRequest containing
the common fields and annotations, make CreateEmailCampaign and
UpdateEmailCampaign extend it, and remove their duplicated declarations; move
ReplyTo and DeliveryOptions from io.mailtrap.model.response.emailcampaigns to a
neutral shared package and update both request DTOs and other references. Apply
the changes in
src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java#L1-L71
and
src/main/java/io/mailtrap/model/request/emailcampaigns/UpdateEmailCampaign.java#L1-L70.

In `@src/test/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImplTest.java`:
- Around line 97-132: Add a dedicated getEmailCampaigns test using a matching
DataMock response and invoke api.getEmailCampaigns with non-null perPage and
token values. Assert the existing response expectations while ensuring the
request serialization covers both pagination query keys and their numeric types.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 46d36535-60d9-43fe-a60c-30f229087592

📥 Commits

Reviewing files that changed from the base of the PR and between b8df273 and a88f4c3.

📒 Files selected for processing (38)
  • README.md
  • examples/java/io/mailtrap/examples/emailcampaigns/EmailCampaignsExample.java
  • src/main/java/io/mailtrap/api/emailcampaigns/EmailCampaigns.java
  • src/main/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImpl.java
  • src/main/java/io/mailtrap/client/MailtrapClient.java
  • src/main/java/io/mailtrap/client/api/MailtrapEmailCampaignsApi.java
  • src/main/java/io/mailtrap/factory/MailtrapClientFactory.java
  • src/main/java/io/mailtrap/model/CampaignState.java
  • src/main/java/io/mailtrap/model/DeliveryMode.java
  • src/main/java/io/mailtrap/model/request/emailcampaigns/CreateEmailCampaign.java
  • src/main/java/io/mailtrap/model/request/emailcampaigns/ScheduleEmailCampaignRequest.java
  • src/main/java/io/mailtrap/model/request/emailcampaigns/TemplateAttributes.java
  • src/main/java/io/mailtrap/model/request/emailcampaigns/UpdateEmailCampaign.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/CampaignRecipientError.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/CurrentStateMetadata.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/DeliveryOptions.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/EmailCampaign.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/EmailCampaignListResponse.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/EmailCampaignResponse.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/EmailCampaignStats.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/EmailCampaignStatsResponse.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/Pagination.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/ReplyTo.java
  • src/main/java/io/mailtrap/model/response/emailcampaigns/Template.java
  • src/test/java/io/mailtrap/api/emailcampaigns/EmailCampaignsImplTest.java
  • src/test/resources/api/emailcampaigns/cancelEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/createEmailCampaignRequest.json
  • src/test/resources/api/emailcampaigns/createEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/getEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/getEmailCampaignStatsResponse.json
  • src/test/resources/api/emailcampaigns/listEmailCampaignsResponse.json
  • src/test/resources/api/emailcampaigns/resetEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/scheduleEmailCampaignRequest.json
  • src/test/resources/api/emailcampaigns/scheduleEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/startEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/terminateEmailCampaignResponse.json
  • src/test/resources/api/emailcampaigns/updateEmailCampaignRequest.json
  • src/test/resources/api/emailcampaigns/updateEmailCampaignResponse.json

Comment on lines +81 to +82
final var scheduled = campaigns.scheduleEmailCampaign(campaignId,
new ScheduleEmailCampaignRequest(OffsetDateTime.of(2026, 6, 1, 9, 0, 0, 0, ZoneOffset.UTC)));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Use a future scheduling timestamp.

2026-06-01T09:00:00Z is already in the past as of July 30, 2026, so this public example can fail when executed. Generate the value relative to the current time or use a clearly future date.

Proposed fix
         final var scheduled = campaigns.scheduleEmailCampaign(campaignId,
-            new ScheduleEmailCampaignRequest(OffsetDateTime.of(2026, 6, 1, 9, 0, 0, 0, ZoneOffset.UTC)));
+            new ScheduleEmailCampaignRequest(
+                OffsetDateTime.now(ZoneOffset.UTC).plusDays(1)
+                    .withHour(9).withMinute(0).withSecond(0).withNano(0)));
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
final var scheduled = campaigns.scheduleEmailCampaign(campaignId,
new ScheduleEmailCampaignRequest(OffsetDateTime.of(2026, 6, 1, 9, 0, 0, 0, ZoneOffset.UTC)));
final var scheduled = campaigns.scheduleEmailCampaign(campaignId,
new ScheduleEmailCampaignRequest(
OffsetDateTime.now(ZoneOffset.UTC).plusDays(1)
.withHour(9).withMinute(0).withSecond(0).withNano(0)));
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@examples/java/io/mailtrap/examples/emailcampaigns/EmailCampaignsExample.java`
around lines 81 - 82, Update the timestamp passed to
EmailCampaignsExample.scheduleEmailCampaign so it is always future-dated when
the example runs, preferably by deriving it from the current time; preserve the
existing UTC OffsetDateTime request construction.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant