To get the most of this official Mailtrap.io PHP SDK:
You can install the package via composer
The Mailtrap API Client is not hard coupled to Guzzle, React, Zend, Symfony HTTP or any other library that sends HTTP messages. Instead, it uses the PSR-18 client abstraction.
This will give you the flexibility to choose what HTTP client you want to use.
If you just want to get started quickly you should run one of the following command (depends on which HTTP client you want to use):
# With symfony http client (recommend)
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-adapterIf you use a framework, install a bridge package for seamless configuration:
These provide service registration and allow you to inject the client where needed with minimal manual bootstrapping.
You should use Composer autoloader in your application to automatically load your dependencies.
The quickest way to send a single transactional email with only the required parameters:
<?php
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;
require __DIR__ . '/vendor/autoload.php';
$mailtrap = MailtrapClient::initSendingEmails(
apiKey: getenv('MAILTRAP_API_KEY') // your API key here https://mailtrap.io/api-tokens
);
$email = (new MailtrapEmail())
->from(new Address('[email protected]'))
->to(new Address('[email protected]'))
->subject('Hello from Mailtrap PHP')
->text('Plain text body');
$response = $mailtrap->send($email);
// Access response body as array (helper optional)
var_dump(ResponseHelper::toArray($response));Mailtrap lets you test safely in the Email Sandbox and then switch to Production (Sending) with one flag.
Example .env variables (or export in shell):
MAILTRAP_API_KEY=your_api_token # https://mailtrap.io/api-tokens
MAILTRAP_USE_SANDBOX=true # true/false toggle
MAILTRAP_INBOX_ID=123456 # Only needed for sandbox
Bootstrap logic:
<?php
use Mailtrap\Helper\ResponseHelper;
use Mailtrap\MailtrapClient;
use Mailtrap\Mime\MailtrapEmail;
use Symfony\Component\Mime\Address;
require __DIR__ . '/vendor/autoload.php';
$apiKey = getenv('MAILTRAP_API_KEY');
$isSandbox = filter_var(getenv('MAILTRAP_USE_SANDBOX'), FILTER_VALIDATE_BOOL);
$inboxId = $isSandbox ? getenv('MAILTRAP_INBOX_ID') : null; // required only for sandbox
$client = MailtrapClient::initSendingEmails(
apiKey: $apiKey,
isSandbox: $isSandbox,
inboxId: $inboxId // null is ignored for production
);
$email = (new MailtrapEmail())
->from(new Address($isSandbox ? '[email protected]' : '[email protected]'))
->to(new Address('[email protected]'))
->subject($isSandbox ? '[SANDBOX] Demo email' : 'Welcome onboard')
->text('This is a minimal body for demonstration purposes.');
$response = $client->send($email);
// Access response body as array (helper optional)
var_dump(ResponseHelper::toArray($response));Bulk stream example (optional) differs only by setting isBulk: true:
$bulkClient = MailtrapClient::initSendingEmails(apiKey: $apiKey, isBulk: true);Recommendations:
- Toggle sandbox with
MAILTRAP_USE_SANDBOX. - Use separate API tokens for Production and Sandbox.
- Keep initialisation in a single factory object/service so that switching is centralised.
<?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';
// Init Mailtrap client depending on your needs
$mailtrap = MailtrapClient::initSendingEmails(
apiKey: getenv('MAILTRAP_API_KEY'), # your API token
isBulk: false, # set to true for bulk email sending (false by default)
isSandbox: false, # set to true for sandbox mode (false by default)
inboxId: null # optional, only for sandbox mode (false by default)
);
$email = (new MailtrapEmail())
->from(new Address('[email protected]', 'Mailtrap Test'))
->replyTo(new Address('[email protected]'))
->to(new Address('[email protected]', 'Jon'))
->priority(Email::PRIORITY_HIGH)
->cc('[email protected]')
->addCc('[email protected]')
->bcc('[email protected]')
->subject('Best practices of building HTML emails')
->text('Hey! Learn the best practices of building HTML emails and play with ready-to-go templates. Mailtrap\'s Guide on How to Build HTML Email is live on our blog')
->html(
'<html>
<body>
<p><br>Hey</br>
Learn the best practices of building HTML emails and play with ready-to-go templates.</p>
<p><a href="https://mailtrap.io/blog/build-html-email/">Mailtrap\'s Guide on How to Build HTML Email</a> is live on our blog</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')
->category('Integration Test')
->customVariables([
'user_id' => '45982',
'batch_id' => 'PSJ-12'
])
;
// Custom email headers (optional)
$email->getHeaders()
->addTextHeader('X-Message-Source', 'domain.com')
->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client')) // the same as addTextHeader
;
try {
$response = $mailtrap->send($email);
var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// OR Template email sending
$email = (new MailtrapEmail())
->from(new Address('[email protected]', 'Mailtrap Test'))
->replyTo(new Address('[email protected]'))
->to(new Address('[email protected]', '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
])
;
try {
$response = $mailtrap->send($email);
var_dump(ResponseHelper::toArray($response)); // body (array)
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}You can find more examples here.
Currently, with this SDK, you can:
- Email API/SMTP
- Send an email (Transactional and Bulk streams)
- Send an email with a Template
- Send a batch of emails (Transactional and Bulk streams)
- Sending domain management CRUD
- Email Sandbox
- Send an email
- Send an email with a template
- Send a batch of emails
- Message management
- Inbox management
- Project management
- Contact management
- Fields CRUD
- Contacts CRUD
- Lists CRUD
- Import/Export
- Events
- General
- Templates CRUD
- Suppressions management (find and delete)
- Billing info
Bug reports and pull requests are welcome on GitHub. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The package is available as open source under the terms of the MIT License.
Everyone interacting in the Mailtrap project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.