Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Mailtrap PHP Client
https://github.com/mailtrap/mailtrap-php
Admin
An official PHP SDK and API client for Mailtrap.io, enabling developers to send transactional and
...
Tokens:
16,833
Snippets:
91
Trust Score:
5.7
Update:
2 weeks ago
Context
Skills
Chat
Benchmark
87.2
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Mailtrap PHP SDK Mailtrap PHP SDK is the official PHP client library for the Mailtrap.io email delivery platform. It provides a unified interface for sending transactional emails, bulk emails, and testing emails in sandbox environments. The SDK is framework-agnostic but includes dedicated bridges for Laravel and Symfony frameworks, making integration seamless with popular PHP frameworks. The SDK supports multiple email sending modes including transactional (single emails), bulk (marketing campaigns), and sandbox (testing). It uses PSR-18 HTTP client abstraction, allowing developers to choose their preferred HTTP client (Symfony HTTP Client or Guzzle). Key features include template-based email sending, batch operations (up to 500 messages per API call), contact management, email suppressions, and comprehensive sandbox testing tools for email validation, spam analysis, and HTML inspection. ## Installation Install the SDK via Composer with your preferred HTTP client. ```bash # With Symfony HTTP client (recommended) composer require railsware/mailtrap-php symfony/http-client nyholm/psr7 # Or with Guzzle HTTP client composer require railsware/mailtrap-php guzzlehttp/guzzle php-http/guzzle7-adapter ``` ## Send Transactional Email Send a single transactional email with minimal configuration using the MailtrapClient. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; require __DIR__ . '/vendor/autoload.php'; try { $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY') // Your API token from https://mailtrap.io/api-tokens ); $email = (new MailtrapEmail()) ->from(new Address('sender@your-domain.com', 'Mailtrap Test')) ->to(new Address('recipient@example.com', 'Jon')) ->subject('Hello from Mailtrap!') ->text('Welcome to Mailtrap Sending!'); $response = $mailtrap->send($email); var_dump(ResponseHelper::toArray($response)); // Output: ['success' => true, 'message_ids' => ['0c7fd939-xxxx-xxxx-xxxx-xxxxxxxxxxxx']] } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Send Full-Featured Email with Attachments Send a richly formatted email with HTML content, attachments, embedded images, custom headers, and tracking variables. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; use Symfony\Component\Mime\Header\UnstructuredHeader; require __DIR__ . '/vendor/autoload.php'; try { $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY') ); $email = (new MailtrapEmail()) ->from(new Address('sender@your-domain.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain.com')) ->to(new Address('recipient@example.com', 'Jon')) ->priority(Email::PRIORITY_HIGH) ->cc('cc@example.com') ->bcc('bcc@example.com') ->subject('Best practices of building HTML emails') ->text('Hey! Learn the best practices of building HTML emails.') ->html( '<html> <body> <p>Hey, Learn the best practices of building HTML emails.</p> <p><a href="https://mailtrap.io/blog/build-html-email/">Mailtrap Guide</a></p> <img src="cid:logo"> </body> </html>' ) ->embed(fopen('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg', 'r'), 'logo', 'image/svg+xml') ->attachFromPath('README.md') ->customVariables([ 'user_id' => '45982', 'batch_id' => 'PSJ-12' ]) ->category('Integration Test'); // Custom email headers (optional) $email->getHeaders() ->addTextHeader('X-Message-Source', 'example.com') ->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client')); $response = $mailtrap->send($email); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Send Email Using Template Send emails using pre-defined Mailtrap templates with dynamic variables. When using templates, do not set subject, text, html, or category fields. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; require __DIR__ . '/vendor/autoload.php'; try { $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY') ); $email = (new MailtrapEmail()) ->from(new Address('sender@your-domain.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain.com')) ->to(new Address('recipient@example.com', 'Jon')) ->templateUuid('bfa432fd-0000-0000-0000-8493da283a69') ->templateVariables([ 'user_name' => 'Jon Bush', 'next_step_link' => 'https://mailtrap.io/', 'get_started_link' => 'https://mailtrap.io/', 'onboarding_video_link' => 'some_video_link', 'company' => [ 'name' => 'Best Company', 'address' => 'Its Address', ], 'products' => [ ['name' => 'Product 1', 'price' => 100], ['name' => 'Product 2', 'price' => 200], ], 'isBool' => true, 'int' => 123 ]); $response = $mailtrap->send($email); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Send Bulk Emails Send marketing and bulk emails using the bulk stream endpoint. Set `isBulk: true` when initializing the client. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; use Symfony\Component\Mime\Email; require __DIR__ . '/vendor/autoload.php'; try { $bulkMailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY'), isBulk: true // Enable bulk sending stream ); $email = (new MailtrapEmail()) ->from(new Address('sender@your-domain.com', 'Mailtrap Test')) ->to(new Address('recipient@example.com', 'Jon')) ->priority(Email::PRIORITY_HIGH) ->subject('Best practices of building HTML emails') ->text('Hey! Learn the best practices of building HTML emails.') ->html('<html><body><p>Learn the best practices!</p></body></html>') ->customVariables([ 'user_id' => '45982', 'batch_id' => 'PSJ-12' ]) ->category('Marketing'); $response = $bulkMailtrap->send($email); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Batch Send Emails Send up to 500 emails in a single API call with batch sending. Results are returned in the same order as requests. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; require __DIR__ . '/vendor/autoload.php'; try { $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY') ); // Base email with common content $baseEmail = (new MailtrapEmail()) ->from(new Address('sender@your-domain.com', 'Mailtrap Test')) ->subject('Batch Email Subject') ->text('Batch email text') ->html('<p>Batch email HTML content</p>'); // Individual recipient emails $recipientEmails = [ (new MailtrapEmail())->to(new Address('recipient1@example.com', 'Recipient 1')), (new MailtrapEmail())->to(new Address('recipient2@example.com', 'Recipient 2')), (new MailtrapEmail())->to(new Address('recipient3@example.com', 'Recipient 3')), ]; $response = $mailtrap->batchSend($recipientEmails, $baseEmail); var_dump(ResponseHelper::toArray($response)); // Output: ['responses' => [['success' => true, 'message_ids' => [...]], ...]] } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Send Sandbox Email for Testing Test emails safely in the Mailtrap sandbox environment before sending to production. Requires `isSandbox: true` and an `inboxId`. ```php <?php use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapClient; use Mailtrap\Mime\MailtrapEmail; use Symfony\Component\Mime\Address; require __DIR__ . '/vendor/autoload.php'; try { $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY'), isSandbox: true, // Enable sandbox mode inboxId: getenv('MAILTRAP_INBOX_ID') // Required for sandbox ); $email = (new MailtrapEmail()) ->from(new Address('test@example.com', 'Mailtrap Test')) ->to(new Address('recipient@example.com', 'Jon')) ->subject('Hello from Mailtrap Sandbox!') ->text('Welcome to Mailtrap Sandbox Testing!'); $response = $mailtrap->send($email); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Sandbox Inbox Management Manage sandbox inboxes for email testing including create, update, delete, and various inbox operations. ```php <?php use Mailtrap\Config; use Mailtrap\DTO\Request\Inbox; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapSandboxClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $sandboxInboxes = (new MailtrapSandboxClient($config))->inboxes($accountId); // Get all inboxes try { $response = $sandboxInboxes->getList(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Create an inbox try { $projectId = getenv('MAILTRAP_PROJECT_ID'); $response = $sandboxInboxes->create($projectId, 'My Test Inbox'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get inbox attributes try { $inboxId = getenv('MAILTRAP_INBOX_ID'); $response = $sandboxInboxes->getInboxAttributes($inboxId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Update an inbox try { $inboxId = getenv('MAILTRAP_INBOX_ID'); $response = $sandboxInboxes->update( $inboxId, new Inbox('New Inbox Name', 'new-email-username') ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Clean all messages in inbox try { $inboxId = getenv('MAILTRAP_INBOX_ID'); $response = $sandboxInboxes->clean($inboxId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Delete inbox try { $inboxId = getenv('MAILTRAP_INBOX_ID'); $response = $sandboxInboxes->delete($inboxId); var_dump($response->getStatusCode()); // 200 on success } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Sandbox Message Operations Retrieve, analyze, and manage messages in sandbox inboxes including HTML analysis and spam scoring. ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapSandboxClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $inboxId = getenv('MAILTRAP_INBOX_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $sandboxMessages = (new MailtrapSandboxClient($config))->messages($accountId, $inboxId); // Get all messages (paginated, 30 per page by default) try { $response = $sandboxMessages->getList(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get a specific message try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->getById($messageId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get message HTML content try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->getHtml($messageId); var_dump(ResponseHelper::toString($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get message as .eml file try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->getEml($messageId); var_dump(ResponseHelper::toString($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get HTML analysis report try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->getHtmlAnalysis($messageId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get spam score analysis try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->getSpamScore($messageId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Delete a message try { $messageId = getenv('MAILTRAP_INBOX_MESSAGE_ID'); $response = $sandboxMessages->delete($messageId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Sandbox Project Management Manage sandbox projects which organize inboxes for email testing workflows. ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapSandboxClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $sandboxProjects = (new MailtrapSandboxClient($config))->projects($accountId); // List all projects try { $response = $sandboxProjects->getList(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get a specific project try { $projectId = getenv('MAILTRAP_PROJECT_ID'); $response = $sandboxProjects->getById($projectId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Create a new project try { $response = $sandboxProjects->create('My New Project'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Update project name try { $projectId = getenv('MAILTRAP_PROJECT_ID'); $response = $sandboxProjects->updateName($projectId, 'Updated Project Name'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Delete project and all its inboxes try { $projectId = getenv('MAILTRAP_PROJECT_ID'); $response = $sandboxProjects->delete($projectId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Contact Management Create, update, delete, and import contacts with custom fields and list management. ```php <?php use Mailtrap\Config; use Mailtrap\DTO\Request\Contact\CreateContact; use Mailtrap\DTO\Request\Contact\UpdateContact; use Mailtrap\DTO\Request\Contact\ImportContact; use Mailtrap\DTO\Request\Contact\CreateContactEvent; use Mailtrap\DTO\Request\Contact\ContactExportFilter; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $contacts = (new MailtrapGeneralClient($config))->contacts($accountId); // Get contact by email try { $response = $contacts->getContactByEmail('john.smith@example.com'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Create a new contact try { $response = $contacts->createContact( CreateContact::init( 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith'], [1, 2] // List IDs to add contact to ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Update contact by email try { $response = $contacts->updateContactByEmail( 'john.smith@example.com', UpdateContact::init( 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith Updated'], [3], // Lists to add [1, 2], // Lists to remove false // Unsubscribe flag ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Bulk import contacts (up to 50,000 per request) try { $contactsToImport = [ new ImportContact( email: 'customer1@example.com', fields: ['first_name' => 'John', 'last_name' => 'Smith'], listIdsIncluded: [1, 2], listIdsExcluded: [4] ), new ImportContact( email: 'customer2@example.com', fields: ['first_name' => 'Jane', 'last_name' => 'Doe'], listIdsIncluded: [1], listIdsExcluded: [] ), ]; $response = $contacts->importContacts($contactsToImport); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Create a contact event try { $response = $contacts->createContactEvent( 'john.smith@example.com', CreateContactEvent::init( 'UserLogin', ['user_id' => 101, 'user_name' => 'John Smith', 'is_active' => true] ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Export contacts with filters try { $filters = [ ContactExportFilter::init('list_id', 'equal', [1, 2]), ContactExportFilter::init('subscription_status', 'equal', 'subscribed'), ]; $response = $contacts->createContactExport($filters); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Delete contact try { $response = $contacts->deleteContactByEmail('john.smith@example.com'); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ## Contact List Management Create, update, and manage contact lists for organizing contacts. ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $contacts = (new MailtrapGeneralClient($config))->contacts($accountId); // Get all contact lists try { $response = $contacts->getAllContactLists(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Get a specific contact list try { $contactListId = 1; $response = $contacts->getContactList($contactListId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Create a new contact list try { $response = $contacts->createContactList('Newsletter Subscribers'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Update a contact list try { $contactListId = 1; $response = $contacts->updateContactList($contactListId, 'Updated List Name'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Delete a contact list try { $contactListId = 1; $response = $contacts->deleteContactList($contactListId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ## Custom Contact Fields Manage custom contact fields for storing additional contact information (up to 40 fields per account). ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $contacts = (new MailtrapGeneralClient($config))->contacts($accountId); // Get all contact fields try { $response = $contacts->getAllContactFields(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Get a specific contact field try { $fieldId = 1; $response = $contacts->getContactField($fieldId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Create a new contact field // Data types: text, integer, float, boolean, date try { $response = $contacts->createContactField( 'Company Name', // Field name (max 80 chars) 'text', // Data type 'company_name_merge_tag' // Merge tag for templates ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Update a contact field (cannot change data_type) try { $fieldId = 1; $response = $contacts->updateContactField( $fieldId, 'Updated Field Name', 'updated_merge_tag' ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Delete a contact field try { $fieldId = 1; $response = $contacts->deleteContactField($fieldId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ## Email Template Management Create, retrieve, update, and delete email templates for consistent email design. ```php <?php use Mailtrap\Config; use Mailtrap\DTO\Request\EmailTemplate; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $emailTemplates = (new MailtrapGeneralClient($config))->emailTemplates($accountId); // Get all email templates try { $response = $emailTemplates->getAllEmailTemplates(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Get a specific template try { $templateId = 12345; $response = $emailTemplates->getEmailTemplate($templateId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Create a new template try { $response = $emailTemplates->createEmailTemplate( EmailTemplate::init( 'Welcome Email', // Name 'Welcome to our service!', // Subject 'Transactional', // Category 'Welcome to our service, {{user_name}}!', // Text body '<div>Welcome to our service, {{user_name}}!</div>' // HTML body ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Update a template try { $templateId = 12345; $response = $emailTemplates->updateEmailTemplate( $templateId, EmailTemplate::init( 'Updated Welcome Email', 'Updated Subject', 'Transactional', 'Updated text body', '<div>Updated HTML body</div>' ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Delete a template try { $templateId = 12345; $response = $emailTemplates->deleteEmailTemplate($templateId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ## Sending Domain Management Manage sending domains for email authentication and deliverability. ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapSendingClient; require __DIR__ . '/vendor/autoload.php'; $accountId = (int) getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $sendingDomains = (new MailtrapSendingClient($config))->domains($accountId); // Get all sending domains try { $response = $sendingDomains->getSendingDomains(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Create a new sending domain try { $response = $sendingDomains->createSendingDomain('example.com'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Get domain by ID try { $domainId = (int) getenv('MAILTRAP_DOMAIN_ID'); $response = $sendingDomains->getDomainById($domainId); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Send domain setup instructions to an email try { $domainId = (int) getenv('MAILTRAP_DOMAIN_ID'); $response = $sendingDomains->sendDomainSetupInstructions($domainId, 'devops@example.com'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } // Delete a sending domain try { $domainId = (int) getenv('MAILTRAP_DOMAIN_ID'); $response = $sendingDomains->deleteSendingDomain($domainId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Suppression Management Manage email suppressions (bounced, unsubscribed, or complained addresses). ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapSendingClient; require __DIR__ . '/vendor/autoload.php'; $accountId = getenv('MAILTRAP_ACCOUNT_ID'); $config = new Config(getenv('MAILTRAP_API_KEY')); $suppressions = (new MailtrapSendingClient($config))->suppressions($accountId); // Get all suppressions (up to 1000 per request) try { $response = $suppressions->getSuppressions(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Get suppressions filtered by email try { $response = $suppressions->getSuppressions('bounced@example.com'); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } // Delete a suppression by ID (UUID) try { $suppressionId = '019706a8-0000-0000-0000-4f26816b467a'; $response = $suppressions->deleteSuppression($suppressionId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ## Account Information Retrieve Mailtrap account information. ```php <?php use Mailtrap\Config; use Mailtrap\Helper\ResponseHelper; use Mailtrap\MailtrapGeneralClient; require __DIR__ . '/vendor/autoload.php'; $config = new Config(getenv('MAILTRAP_API_KEY')); $generalAccounts = (new MailtrapGeneralClient($config))->accounts(); // Get list of accounts try { $response = $generalAccounts->getList(); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Laravel Integration Configure Mailtrap as a Laravel mail transport with environment-based configuration. ```php // config/mail.php <?php return [ 'mailers' => [ 'mailtrap-sdk' => [ 'transport' => 'mailtrap-sdk' ], ] ]; // .env file // For Production Sending: MAIL_MAILER="mailtrap-sdk" MAILTRAP_HOST="send.api.mailtrap.io" MAILTRAP_API_KEY="YOUR_API_KEY_HERE" // For Bulk Sending: // MAILTRAP_HOST="bulk.api.mailtrap.io" // For Sandbox Testing: // MAILTRAP_HOST="sandbox.api.mailtrap.io" // MAILTRAP_INBOX_ID=1000001 ``` ```php // app/Mail/WelcomeMail.php <?php namespace App\Mail; use Illuminate\Mail\Mailable; use Illuminate\Mail\Mailables\Address; use Illuminate\Mail\Mailables\Content; use Illuminate\Mail\Mailables\Envelope; use Mailtrap\EmailHeader\CategoryHeader; use Mailtrap\EmailHeader\CustomVariableHeader; use Symfony\Component\Mime\Email; class WelcomeMail extends Mailable { private string $name; public function __construct(string $name) { $this->name = $name; } public function envelope(): Envelope { return new Envelope( from: new Address('sender@your-domain.com', 'Your App'), subject: 'Welcome Mail', using: [ function (Email $email) { $email->getHeaders() ->add(new CustomVariableHeader('user_id', '12345')) ->add(new CategoryHeader('Welcome')); }, ] ); } public function content(): Content { return new Content( view: 'mail.welcome', with: ['name' => $this->name], ); } } // Usage in controller or command use App\Mail\WelcomeMail; use Illuminate\Support\Facades\Mail; Mail::to('recipient@example.com')->send(new WelcomeMail('John')); ``` ## Symfony Integration Configure Mailtrap as a Symfony Mailer transport. ```yaml # config/services.yaml services: Mailtrap\Bridge\Transport\MailtrapSdkTransportFactory: tags: - { name: 'mailer.transport_factory' } ``` ```bash # .env # For Production Sending: MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@send.api.mailtrap.io # For Bulk Sending: # MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@bulk.api.mailtrap.io # For Sandbox Testing: # MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@sandbox.api.mailtrap.io?inboxId=1000001 ``` ```php <?php // src/Controller/EmailController.php use Mailtrap\Mime\MailtrapEmail; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\Mailer\Transport\TransportInterface; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Mime\Email; use Symfony\Component\Routing\Annotation\Route; class EmailController extends AbstractController { public function __construct(private TransportInterface $transport) { } #[Route('/send-email', name: 'send_email', methods: ['GET'])] public function sendEmail(): JsonResponse { $message = (new MailtrapEmail()) ->from('sender@your-domain.com') ->to('recipient@example.com') ->subject('Test email') ->text('Plain text content') ->html('<p>HTML content</p>') ->priority(Email::PRIORITY_HIGH) ->category('notification') ->customVariables(['user_id' => '123']); $response = $this->transport->send($message); return new JsonResponse(['messageId' => $response->getMessageId()]); } } ``` ## Summary The Mailtrap PHP SDK provides a comprehensive solution for PHP applications requiring reliable email delivery and testing capabilities. Primary use cases include transactional email sending (order confirmations, password resets, notifications), bulk marketing campaigns, and thorough email testing in sandbox environments before production deployment. The SDK's unified API allows developers to seamlessly switch between production and sandbox modes using simple configuration flags, making it ideal for development workflows that require email testing without risking real email delivery. Integration patterns typically involve initializing the appropriate client (`MailtrapClient::initSendingEmails()` for sending, `MailtrapSandboxClient` for testing, `MailtrapGeneralClient` for account management) with API credentials, then using the fluent `MailtrapEmail` builder to construct messages. For Laravel and Symfony applications, the SDK provides native bridge packages that integrate with each framework's mail system, allowing developers to use familiar patterns while gaining access to Mailtrap-specific features like templates, categories, and custom variables. The PSR-18 HTTP client abstraction ensures compatibility with any HTTP client library, giving developers flexibility in their infrastructure choices.