# Mailtrap PHP Client ## Introduction The Mailtrap PHP client is an official SDK for integrating Mailtrap's email services into PHP applications. Mailtrap provides both a sandbox environment for testing emails during development and production-level transactional and bulk email sending capabilities. The SDK uses PSR-18 HTTP client abstraction, making it compatible with any HTTP client implementation (Guzzle, Symfony HTTP Client, etc.), and extends Symfony's MIME component for email construction. This library enables developers to send transactional emails, test emails in a sandbox environment, manage sending domains, handle contact lists, work with email templates, and access detailed analytics. It supports advanced features like template variables, custom headers, attachments, batch sending, and comprehensive contact management with custom fields and events. The SDK provides separate client interfaces for general operations, sandbox testing, transactional sending, and bulk sending, with seamless switching between environments. ## API Functions and Code Examples ### Initialize Client for Sending Emails Quick initialization for transactional or bulk email sending with optional sandbox mode. ```php from(new Address('sender@example.com', 'Sender Name')) ->to(new Address('recipient@example.com', 'Recipient Name')) ->subject('Hello from Mailtrap PHP') ->text('Plain text body content') ->html('

HTML body content

'); $response = $mailtrap->send($email); var_dump(ResponseHelper::toArray($response)); // Output: ['success' => true, 'message_ids' => [...]] } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ### Send Email with Full Features Send email with attachments, embedded images, custom variables, categories, and custom headers. ```php from(new Address('example@your-domain.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain.com')) ->to(new Address('email@example.com', 'Jon')) ->priority(Email::PRIORITY_HIGH) ->cc('qa@example.com') ->addCc('staging@example.com') ->bcc('dev@example.com') ->subject('Best practices of building HTML emails') ->text('Hey! Learn the best practices of building HTML emails.') ->html( '

Hey! Learn the best practices of building HTML emails.

Guide

' ) ->embed(fopen('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg', 'r'), 'logo', 'image/svg+xml') ->attachFromPath('/path/to/file.pdf') ->category('Integration Test') ->customVariables([ 'user_id' => '45982', 'batch_id' => 'PSJ-12' ]); // Add custom headers $email->getHeaders() ->addTextHeader('X-Message-Source', 'domain.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 with Template Send email using pre-defined template with dynamic variables. ```php from(new Address('example@your-domain.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain.com')) ->to(new Address('example@gmail.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' => 'https://example.com/video', '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"; } ``` ### Batch Send Emails Send multiple emails in a single API call (up to 500 messages, 50 MB total). ```php from(new Address('example@your-domain.com', 'Mailtrap Test')) ->subject('Batch Email Subject') ->text('Batch email text') ->html('

Batch email text

'); $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); // Response returns success/error for each message $result = ResponseHelper::toArray($response); var_dump($result); // Output: ['messages' => [['success' => true], ['success' => true], ...]] } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ### Batch Send with Template and Per-Recipient Variables Send templated emails to multiple recipients with customized variables for each. ```php from(new Address('example@your-domain.com', 'Mailtrap Test')) ->templateUuid('bfa432fd-0000-0000-0000-8493da283a69') ->templateVariables([ 'user_name' => 'Default Name', 'next_step_link' => 'https://mailtrap.io/', 'company' => [ 'name' => 'Best Company', 'address' => 'Its Address', ], ]); $recipientEmails = [ (new MailtrapEmail()) ->to(new Address('recipient1@example.com', 'Recipient 1')) ->templateVariables([ 'user_name' => 'Custom User 1', ]), (new MailtrapEmail()) ->to(new Address('recipient2@example.com', 'Recipient 2')) ->templateVariables([ 'user_name' => 'Custom User 2', ]), ]; $response = $mailtrap->batchSend($recipientEmails, $baseEmail); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ### Send Email to Sandbox (Testing) Send test emails to sandbox inbox for debugging and development. ```php from(new Address('mailtrap@example.com', 'Mailtrap Test')) ->replyTo(new Address('reply@example.com')) ->to(new Address('email@example.com', 'Jon')) ->subject('Best practices of building HTML emails') ->text('Hey! Learn the best practices.') ->html('

Test email content

') ->category('Integration Test') ->customVariables([ 'user_id' => '45982', 'batch_id' => 'PSJ-12' ]); $response = $mailtrap->send($email); // Access full response details var_dump($response->getHeaders()); var_dump($response->getStatusCode()); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ### Manage Sending Domains Create, retrieve, and manage verified sending domains. ```php domains($accountId); try { // Get all sending domains $response = $sendingDomains->getSendingDomains(); var_dump(ResponseHelper::toArray($response)); // Create new sending domain $response = $sendingDomains->createSendingDomain('example.com'); var_dump(ResponseHelper::toArray($response)); // Get specific domain by ID $domainId = 12345; $response = $sendingDomains->getDomainById($domainId); var_dump(ResponseHelper::toArray($response)); // Send setup instructions via email $response = $sendingDomains->sendDomainSetupInstructions($domainId, 'devops@example.com'); var_dump(ResponseHelper::toArray($response)); // Delete domain $response = $sendingDomains->deleteSendingDomain($domainId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ### Manage Contact Lists Create and manage contact lists for email campaigns. ```php contacts($accountId); try { // Get all contact lists $response = $contacts->getAllContactLists(); var_dump(ResponseHelper::toArray($response)); // Get specific contact list $listId = 1; $response = $contacts->getContactList($listId); var_dump(ResponseHelper::toArray($response)); // Create new contact list $response = $contacts->createContactList('New Contact List'); var_dump(ResponseHelper::toArray($response)); // Update contact list $response = $contacts->updateContactList($listId, 'Updated Contact List Name'); var_dump(ResponseHelper::toArray($response)); // Delete contact list $response = $contacts->deleteContactList($listId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Manage Contacts Create, update, retrieve, and delete individual contacts. ```php contacts($accountId); try { // Create contact $response = $contacts->createContact( CreateContact::init( 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith'], [1, 2] // List IDs ) ); var_dump(ResponseHelper::toArray($response)); // Get contact by ID or email $response = $contacts->getContactById('019706a8-0000-0000-0000-4f26816b467a'); $response = $contacts->getContactByEmail('john.smith@example.com'); var_dump(ResponseHelper::toArray($response)); // Update contact $response = $contacts->updateContactById( '019706a8-0000-0000-0000-4f26816b467a', UpdateContact::init( 'john.smith@example.com', ['first_name' => 'John', 'last_name' => 'Smith'], [3], // List IDs to add [1, 2], // List IDs to remove true // Unsubscribe flag ) ); var_dump(ResponseHelper::toArray($response)); // Delete contact $response = $contacts->deleteContactById('019706a8-0000-0000-0000-4f26816b467a'); $response = $contacts->deleteContactByEmail('john.smith@example.com'); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Manage Contact Fields Create and manage custom fields for contact attributes. ```php contacts($accountId); try { // Get all contact fields $response = $contacts->getAllContactFields(); var_dump(ResponseHelper::toArray($response)); // Get specific field $fieldId = 1; $response = $contacts->getContactField($fieldId); var_dump(ResponseHelper::toArray($response)); // Create contact field (max 40 fields per account) $response = $contacts->createContactField( 'New Field Name', 'text', // Allowed: text, integer, float, boolean, date 'new_field_merge_tag' ); var_dump(ResponseHelper::toArray($response)); // Update contact field (cannot change data_type) $response = $contacts->updateContactField( $fieldId, 'Updated Field Name', 'updated_field_merge_tag' ); var_dump(ResponseHelper::toArray($response)); // Delete field $response = $contacts->deleteContactField($fieldId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Import Contacts in Bulk Import up to 50,000 contacts per request with custom fields and list assignments. ```php contacts($accountId); try { $contactsToImport = [ new ImportContact( email: 'customer1@example.com', fields: ['first_name' => 'John', 'last_name' => 'Smith', 'zip_code' => 11111], listIdsIncluded: [1, 2], listIdsExcluded: [4, 5] ), new ImportContact( email: 'customer2@example.com', fields: ['first_name' => 'Joe', 'last_name' => 'Doe', 'zip_code' => 22222], listIdsIncluded: [1], listIdsExcluded: [4] ), ]; $response = $contacts->importContacts($contactsToImport); $result = ResponseHelper::toArray($response); var_dump($result); // Output: ['import_id' => 123, 'status' => 'processing'] // Check import status $importId = $result['import_id']; $response = $contacts->getContactImport($importId); var_dump(ResponseHelper::toArray($response)); // Output: ['status' => 'finished', 'imported' => 2, 'failed' => 0] } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Export Contacts with Filters Create contact export with filters and retrieve download URL. ```php contacts($accountId); try { // Create export with filters $filters = [ ContactExportFilter::init('list_id', 'equal', [1, 2]), ContactExportFilter::init('subscription_status', 'equal', 'subscribed'), ]; $response = $contacts->createContactExport($filters); $result = ResponseHelper::toArray($response); var_dump($result); // Output: ['export_id' => 456, 'status' => 'processing'] // Poll for export completion $exportId = $result['export_id']; $response = $contacts->getContactExport($exportId); $exportData = ResponseHelper::toArray($response); var_dump($exportData); // Output: ['status' => 'finished', 'url' => 'https://...', 'expires_at' => '...'] // Download file when status is 'finished' and url is not null if ($exportData['status'] === 'finished' && !empty($exportData['url'])) { file_put_contents('contacts_export.csv', file_get_contents($exportData['url'])); } } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Create Contact Events Track custom events for contacts (user actions, activity tracking). ```php contacts($accountId); try { $response = $contacts->createContactEvent( 'john.smith@example.com', // Contact identifier (email or UUID) CreateContactEvent::init( 'UserLogin', [ 'user_id' => 101, 'user_name' => 'John Smith', 'is_active' => true, 'login_time' => '2025-10-28T10:30:00Z', 'ip_address' => '192.168.1.1', 'device' => 'mobile' ] ) ); var_dump(ResponseHelper::toArray($response)); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Manage Email Templates Create, update, and manage reusable email templates. ```php emailTemplates($accountId); try { // Get all templates $response = $emailTemplates->getAllEmailTemplates(); var_dump(ResponseHelper::toArray($response)); // Get specific template $templateId = 12345; $response = $emailTemplates->getEmailTemplate($templateId); var_dump(ResponseHelper::toArray($response)); // Create new template $response = $emailTemplates->createEmailTemplate( EmailTemplate::init( 'Welcome Email', 'Welcome to our service!', 'Transactional', 'Welcome to our service!', '

Welcome

Thanks for joining!

' ) ); var_dump(ResponseHelper::toArray($response)); // Update template $response = $emailTemplates->updateEmailTemplate( $templateId, EmailTemplate::init( 'Updated Welcome Email', 'Updated Subject', 'Transactional', 'Updated Text Body', '

Updated HTML Body

' ) ); var_dump(ResponseHelper::toArray($response)); // Delete template $response = $emailTemplates->deleteEmailTemplate($templateId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Manage Suppressions Retrieve and delete email suppressions (bounces, unsubscribes, spam complaints). ```php suppressions($accountId); try { // Get all suppressions (up to 1000 per request) $response = $suppressions->getSuppressions(); var_dump(ResponseHelper::toArray($response)); // Get suppressions by email $response = $suppressions->getSuppressions('some_email@mail.com'); var_dump(ResponseHelper::toArray($response)); // Delete suppression by ID $suppressionId = '019706a8-0000-0000-0000-4f26816b467a'; $response = $suppressions->deleteSuppression($suppressionId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), PHP_EOL; } ``` ### Retrieve and Analyze Sandbox Messages Access sandbox messages with detailed analysis, spam scores, and various formats. ```php messages($accountId, $inboxId); try { // Get message list with pagination and search $response = $sandboxMessages->getList(); var_dump(ResponseHelper::toArray($response)); $messageId = 3000000001; // Get specific message details $response = $sandboxMessages->getById($messageId); var_dump(ResponseHelper::toArray($response)); // Get message source $response = $sandboxMessages->getSource($messageId); var_dump(ResponseHelper::toString($response)); // Get message as .eml file $response = $sandboxMessages->getEml($messageId); file_put_contents('message.eml', ResponseHelper::toString($response)); // Get HTML body $response = $sandboxMessages->getHtml($messageId); var_dump(ResponseHelper::toString($response)); // Get raw message $response = $sandboxMessages->getRaw($messageId); var_dump(ResponseHelper::toString($response)); // Get text body $response = $sandboxMessages->getText($messageId); var_dump(ResponseHelper::toString($response)); // Get HTML analysis $response = $sandboxMessages->getHtmlAnalysis($messageId); var_dump(ResponseHelper::toArray($response)); // Get spam score $response = $sandboxMessages->getSpamScore($messageId); var_dump(ResponseHelper::toArray($response)); // Mark as read $response = $sandboxMessages->markAsRead($messageId); var_dump(ResponseHelper::toArray($response)); // Delete message $response = $sandboxMessages->delete($messageId); var_dump($response->getStatusCode()); } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } ``` ## Summary and Integration The Mailtrap PHP client serves three primary use cases: development testing in sandbox environments, production transactional email delivery, and bulk email campaigns. For development workflows, the sandbox mode captures all outbound emails for inspection without delivering them to recipients, providing detailed analytics including spam scores and HTML validation. For production, the transactional API handles user notifications, password resets, order confirmations, and other triggered emails with reliable delivery. The bulk API efficiently manages newsletter campaigns and marketing emails to large contact lists with sophisticated segmentation and personalization. Integration is straightforward across frameworks using Composer dependency management and PSR-18 HTTP client abstraction. Laravel and Symfony developers can leverage framework-specific bridge packages for automatic service registration and dependency injection. The SDK's fluent interface built on Symfony MIME components enables expressive email construction, while comprehensive contact management APIs support full-featured CRM operations including custom fields, list segmentation, bulk imports/exports, and event tracking. Environment-based configuration allows seamless switching between sandbox testing and production sending, making the library suitable for all stages of the development lifecycle.