Skip to content

[3.2.0] Add Email Templates API functionality #39

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 12, 2025

Conversation

gaalferov
Copy link
Collaborator

@gaalferov gaalferov commented Jun 6, 2025

Motivation

Support new functionality (Email templates)
https://help.mailtrap.io/article/105-email-templates

Changes

  • Added new sub layer EmailTemplates into MailtrapGeneralClient
    • getAllEmailTemplates
    • getEmailTemplate
    • createEmailTemplate
    • updateEmailTemplate
    • deleteEmailTemplate
  • Added Contact Lists API methods
    • getContactList
    • createContactList
    • updateContactList
    • deleteContactList
  • Added new tests
  • Added examples

How to test

composer test

OR run PHP code from the example

(new MailtrapGeneralClient($config))
    ->emailTemplates($accountId)
    ->getAllEmailTemplates();

(new MailtrapGeneralClient($config))
    ->contacts($accountId)
    ->getContactList(1);

Summary by CodeRabbit

  • New Features

    • Introduced a "Get contact" API endpoint, allowing retrieval of contacts by ID or email.
    • Added API support for managing Email Templates, including creating, updating, retrieving, and deleting templates.
    • Added Contact Lists API functionality for creating, retrieving, updating, and deleting contact lists.
  • Examples

    • Provided new example scripts for using the Contact Lists and Email Templates APIs.
    • Updated deletion examples to display HTTP status codes instead of full response bodies.
  • Bug Fixes

    • Improved error handling to ensure error messages are always present when decoding HTTP responses fails.
  • Tests

    • Added comprehensive tests for the new contact retrieval, Contact Lists, and Email Template management features.

Copy link

coderabbitai bot commented Jun 6, 2025

Walkthrough

This update introduces a new "Get contact" API endpoint and comprehensive email template management via API, reflected in new classes, methods, and usage examples. Supporting tests and documentation are added or updated. Several example scripts now print HTTP status codes after delete operations instead of response bodies.

Changes

Files / Groups Change Summary
CHANGELOG.md Added entry for version 3.2.0, documenting new "Get contact" and email template API features.
examples/general/contacts.php Added examples for Contact Lists CRUD and retrieving contacts by ID/email; delete example now prints status code.
examples/general/emailTemplates.php New example script demonstrating all email template API operations with error handling.
examples/general/users.php,
examples/testing/inboxes.php,
examples/testing/messages.php,
examples/testing/projects.php
Modified delete operation output to print HTTP status code instead of response body.
src/Api/General/Contact.php Added methods for managing Contact Lists (get, create, update, delete) and retrieving contacts by ID or email.
src/Api/General/EmailTemplate.php New class for managing email templates: CRUD methods, constructor, and endpoint logic.
src/DTO/Request/EmailTemplate.php New DTO class for email template data with constructor, factory method, getters, and array conversion.
src/Exception/HttpClientException.php Added default error message if response body is empty after failed JSON/type conversion.
src/MailtrapGeneralClient.php Added API mapping and method annotation for emailTemplates endpoint.
tests/Api/General/ContactTest.php Added tests for Contact Lists and contact retrieval by ID/email, including success and error cases.
tests/Api/General/EmailTemplateTest.php New test class covering all email template API client methods and error handling.
tests/MailtrapGeneralClientTest.php Updated provider to support instantiating emailTemplates mapping with account ID.

Sequence Diagram(s)

sequenceDiagram
    participant ClientApp
    participant MailtrapGeneralClient
    participant EmailTemplateAPI
    participant MailtrapAPI

    ClientApp->>MailtrapGeneralClient: emailTemplates(accountId)
    MailtrapGeneralClient->>EmailTemplateAPI: instantiate(accountId)
    ClientApp->>EmailTemplateAPI: createEmailTemplate(dto)
    EmailTemplateAPI->>MailtrapAPI: POST /accounts/{id}/email-templates
    MailtrapAPI-->>EmailTemplateAPI: Response
    EmailTemplateAPI-->>ClientApp: Response

    ClientApp->>EmailTemplateAPI: getAllEmailTemplates()
    EmailTemplateAPI->>MailtrapAPI: GET /accounts/{id}/email-templates
    MailtrapAPI-->>EmailTemplateAPI: Response
    EmailTemplateAPI-->>ClientApp: Response

    ClientApp->>EmailTemplateAPI: updateEmailTemplate(templateId, dto)
    EmailTemplateAPI->>MailtrapAPI: PATCH /accounts/{id}/email-templates/{templateId}
    MailtrapAPI-->>EmailTemplateAPI: Response
    EmailTemplateAPI-->>ClientApp: Response

    ClientApp->>EmailTemplateAPI: deleteEmailTemplate(templateId)
    EmailTemplateAPI->>MailtrapAPI: DELETE /accounts/{id}/email-templates/{templateId}
    MailtrapAPI-->>EmailTemplateAPI: Response
    EmailTemplateAPI-->>ClientApp: Response
Loading
sequenceDiagram
    participant ClientApp
    participant MailtrapGeneralClient
    participant ContactAPI
    participant MailtrapAPI

    ClientApp->>MailtrapGeneralClient: contacts()
    MailtrapGeneralClient->>ContactAPI: instantiate()
    ClientApp->>ContactAPI: getContactById(contactId)
    ContactAPI->>MailtrapAPI: GET /contacts/{contactId}
    MailtrapAPI-->>ContactAPI: Response
    ContactAPI-->>ClientApp: Response

    ClientApp->>ContactAPI: getContactByEmail(email)
    ContactAPI->>MailtrapAPI: GET /contacts/{email}
    MailtrapAPI-->>ContactAPI: Response
    ContactAPI-->>ClientApp: Response
Loading

Poem

Hopping through code with a twitch of my nose,
New endpoints and features—how quickly it grows!
Email templates now managed with ease,
Contacts found swiftly—developers pleased.
With status codes clear and examples anew,
This bunny’s delighted to share them with you!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@gaalferov gaalferov marked this pull request as ready for review June 10, 2025 16:26
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
examples/general/contacts.php (1)

117-118: Consider adding context for the status code output.

While printing the status code is more concise, consider adding a comment explaining what successful delete status codes to expect (e.g., 200, 204).

-    // Print the response status code
+    // Print the response status code (200 or 204 indicates successful deletion)
     var_dump($response->getStatusCode());
examples/general/emailTemplates.php (1)

1-109: Good example structure with comprehensive API coverage.

The example script effectively demonstrates all email template operations with proper error handling. However, consider adding comments about replacing the hardcoded template IDs with actual values.

Consider adding a more prominent comment about the hardcoded template IDs:

-    $templateId = 12345; // Replace with a valid template ID
+    $templateId = 12345; // IMPORTANT: Replace with an actual template ID from your account
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b48e1d1 and 2936a5e.

📒 Files selected for processing (15)
  • CHANGELOG.md (1 hunks)
  • examples/general/contacts.php (2 hunks)
  • examples/general/emailTemplates.php (1 hunks)
  • examples/general/users.php (1 hunks)
  • examples/testing/inboxes.php (1 hunks)
  • examples/testing/messages.php (1 hunks)
  • examples/testing/projects.php (1 hunks)
  • src/Api/General/Contact.php (2 hunks)
  • src/Api/General/EmailTemplate.php (1 hunks)
  • src/DTO/Request/EmailTemplate.php (1 hunks)
  • src/Exception/HttpClientException.php (1 hunks)
  • src/MailtrapGeneralClient.php (2 hunks)
  • tests/Api/General/ContactTest.php (1 hunks)
  • tests/Api/General/EmailTemplateTest.php (1 hunks)
  • tests/MailtrapGeneralClientTest.php (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
tests/MailtrapGeneralClientTest.php (1)
tests/MailtrapTestCase.php (1)
  • getConfigMock (38-57)
src/Api/General/Contact.php (1)
src/Api/AbstractApi.php (2)
  • handleResponse (84-111)
  • httpGet (34-41)
🔇 Additional comments (16)
examples/testing/projects.php (1)

92-93: Good standardization of delete operation feedback.

Changing from dumping the full response body to just the HTTP status code makes sense for delete operations, as the status code clearly indicates success or failure.

examples/testing/messages.php (1)

200-201: Consistent with delete operation standardization.

This change aligns with the standardization effort across example scripts to output status codes for delete operations instead of full response bodies.

examples/testing/inboxes.php (1)

75-76: Consistent delete operation feedback pattern.

Good consistency in applying the status code output pattern for delete operations across different resource examples.

examples/general/users.php (1)

42-43: Completes the delete operation standardization.

This change completes the consistent pattern of outputting status codes for delete operations across all example scripts.

src/Api/General/Contact.php (2)

35-55: Well-designed contact retrieval methods.

The new getContactById and getContactByEmail methods follow the established pattern of delegating to a private method, maintaining consistency with existing update and delete operations in this class.


121-132: Proper implementation of contact retrieval logic.

The private getContact method correctly:

  • Uses urlencode() to safely handle special characters in IDs or emails
  • Follows the established pattern of using handleResponse() for error handling
  • Constructs the URL path consistently with other methods in the class
CHANGELOG.md (1)

1-4: LGTM! Verify the release date.

The changelog entry accurately documents the new features and follows the established format. However, please verify that the date "2025-06-12" is correct, as it appears to be in the future.

src/Exception/HttpClientException.php (1)

32-34: Excellent defensive programming practice.

Adding a fallback error message when the response body is empty ensures consistent error reporting and improves debugging experience. This prevents scenarios where users would see empty error messages after API failures.

examples/general/contacts.php (1)

29-45: Good example demonstrating new contact retrieval functionality.

The example clearly shows both ways to retrieve a contact (by ID and by email) with proper error handling. This will help users understand the new API endpoints.

src/MailtrapGeneralClient.php (2)

12-12: Perfect integration following established patterns.

The method annotation correctly shows the EmailTemplate API requires an accountId parameter, consistent with other account-scoped APIs.


23-23: Consistent API mapping integration.

The EmailTemplate class is properly added to the API_MAPPING, enabling the magic method functionality that users expect from the general client.

tests/MailtrapGeneralClientTest.php (1)

31-31: Proper test coverage for new EmailTemplate API mapping.

The test correctly includes 'emailTemplates' in the match expression, ensuring it gets instantiated with the required accountId parameter like other account-scoped APIs.

tests/Api/General/ContactTest.php (1)

58-95: LGTM! Well-structured test methods with proper coverage.

The new test methods testGetContactById and testGetContactByEmail follow the established testing patterns and provide good coverage for the contact retrieval functionality. The URL encoding for email addresses is properly tested.

tests/Api/General/EmailTemplateTest.php (1)

1-213: Excellent comprehensive test coverage.

The test class provides thorough coverage of all email template operations including error scenarios. The mocking is properly implemented and assertions are comprehensive.

src/DTO/Request/EmailTemplate.php (1)

8-64: Clean and well-structured DTO implementation.

The EmailTemplate DTO follows good practices with:

  • Property promotion in constructor
  • Static factory method for convenience
  • Proper getter methods
  • Correct snake_case conversion in toArray() for API compatibility
src/Api/General/EmailTemplate.php (1)

15-97: Well-implemented API client following established patterns.

The EmailTemplate API client is properly structured with:

  • Correct inheritance and interface implementation
  • Consistent URL path construction
  • Appropriate HTTP methods for each operation
  • Proper response handling through handleResponse()

The implementation follows the existing codebase patterns effectively.

@gaalferov gaalferov changed the title Add Email Templates API functionality [3.2.0] Add Email Templates API functionality Jun 11, 2025
Copy link

@coderabbitai coderabbitai bot left a comment

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 (5)
examples/general/contacts.php (3)

1-2: Add strict_types and fail-fast env-var checks at script start

The examples are a good reference, but omitting declare(strict_types=1); and silent use of getenv() can lead to subtle type issues or mysterious 401s when the vars are unset.
Consider:

 <?php
+declare(strict_types=1);
+
+$accountId = getenv('MAILTRAP_ACCOUNT_ID');
+$apiKey    = getenv('MAILTRAP_API_KEY');
+
+if (!$accountId || !$apiKey) {
+    fwrite(STDERR, "Please export MAILTRAP_ACCOUNT_ID and MAILTRAP_API_KEY\n");
+    exit(1);
+}

This keeps the sample robust while remaining concise.


30-44: Avoid hard-coded IDs in examples; chain the create → read flow

All list-centric samples use $contactListId = 1, which won’t exist in most accounts. New users will copy-paste and immediately receive 404s. Better UX:

  1. Create the list.
  2. Extract the returned ID.
  3. Use that ID for get / update / delete.

This keeps the snippet copy-pastable without edits.


88-90: Prefer echo $response->getStatusCode(), PHP_EOL over var_dump for scalars

var_dump adds noise (int(204)). A plain echo is cleaner for scalar output and consistent with the preceding pretty-printed array dumps.

tests/Api/General/ContactTest.php (2)

91-109: Use 201 status for “create” happy-path to mirror REST conventions

createContactList currently mocks a 200. Mailtrap’s API (and the rest of the SDK) usually returns 201 Created for resource creation—see createContact test. Switching to 201:

- new Response(200, ['Content-Type' => 'application/json'], ...)
+ new Response(201, ['Content-Type' => 'application/json'], ...)

keeps the expectations realistic and prevents accidental lax assertions.


138-144: Minor duplication: consider helper for base path composition

The literal concatenation of AbstractApi::DEFAULT_HOST . '/api/accounts/' . self::FAKE_ACCOUNT_ID is repeated ~20×.
A small private function url(string $suffix): string in the test class would reduce noise and future proof path changes.

Not blocking, just readability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2936a5e and 4850fe1.

📒 Files selected for processing (4)
  • CHANGELOG.md (1 hunks)
  • examples/general/contacts.php (2 hunks)
  • src/Api/General/Contact.php (2 hunks)
  • tests/Api/General/ContactTest.php (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • CHANGELOG.md
  • src/Api/General/Contact.php
🧰 Additional context used
🧬 Code Graph Analysis (1)
examples/general/contacts.php (2)
src/Api/General/Contact.php (6)
  • getContactList (41-46)
  • createContactList (54-62)
  • updateContactList (71-79)
  • deleteContactList (87-92)
  • getContactById (100-103)
  • getContactByEmail (111-114)
src/Helper/ResponseHelper.php (1)
  • ResponseHelper (14-37)

@gaalferov gaalferov merged commit 7e04265 into main Jun 12, 2025
20 checks passed
@gaalferov gaalferov deleted the feature/new-api-functionality branch June 12, 2025 11:29
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.

3 participants