# 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.
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!', 'Thanks for joining!