### Full-featured usage example: sending emails and templates with Mailtrap PHP client Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Complete example showing how to initialize the Mailtrap client for sending emails, build an email with MailtrapEmail, add custom headers, send it, and then send a template-based email. Requires the MAILTRAP_API_KEY environment variable and the Symfony Mailer components. The example demonstrates both regular and template sending, with error handling and response inspection. ```php from(new Address('example@your-domain-here.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain-here.com')) ->to(new Address('email@example.com', 'Jon')) ->priority(Email::PRIORITY_HIGH) ->cc('mailtrapqa@example.com') ->addCc('staging@example.com') ->bcc('mailtrapdev@example.com') ->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( '


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

' ) ->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('example@your-domain-here.com', 'Mailtrap Test')) ->replyTo(new Address('reply@your-domain-here.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' => '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"; } ``` -------------------------------- ### Run minimal example from project root Source: https://github.com/railsware/mailtrap-php/blob/main/examples/README.md Executes the minimal sending example from the project root. For batch examples, ensure the stream (bulk vs transactional vs sandbox) matches your API token and domain verification status. ```bash php examples/sending/minimal.php ``` -------------------------------- ### Install with Symfony HTTP Client Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Use this command to install the Mailtrap PHP client with the Symfony HTTP client and Nyholm PSR-7, recommended for quick setup. ```bash composer require railsware/mailtrap-php symfony/http-client nyholm/psr7 ``` -------------------------------- ### Install with Guzzle HTTP Client Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Use this command to install the Mailtrap PHP client with the Guzzle HTTP client and the Guzzle 7 adapter. ```bash composer require railsware/mailtrap-php guzzlehttp/guzzle php-http/guzzle7-adapter ``` -------------------------------- ### Run the Send Welcome Mail Command Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Executes the Artisan command to send the welcome email using the configured Mailable. ```bash php artisan send-welcome-mail ``` -------------------------------- ### Install with Guzzle HTTP client Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Alternative installation using the Guzzle HTTP client instead of Symfony. Requires Composer. ```bash # Or with guzzle http client composer require railsware/mailtrap-php guzzlehttp/guzzle php-http/guzzle7-adapter symfony/mailer ``` -------------------------------- ### WelcomeMail Mailable Class Configuration Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Example Mailable class that configures envelope, content, attachments, and headers. Includes Mailtrap custom headers for category and custom variables, and uses a Blade view for the email body. ```php # app/Mail/WelcomeMail.php name = $name; } /** * Get the message envelope. */ public function envelope(): Envelope { return new Envelope( from: new Address('jeffrey@example.com', 'Jeffrey Way'), replyTo: [ new Address('taylor@example.com', 'Taylor Otwell'), ], subject: 'Welcome Mail', using: [ function (Email $email) { // Headers $email->getHeaders() ->addTextHeader('X-Message-Source', 'example.com') ->add(new UnstructuredHeader('X-Mailer', 'Mailtrap PHP Client')) ; // Custom Variables $email->getHeaders() ->add(new CustomVariableHeader('user_id', '45982')) ->add(new CustomVariableHeader('batch_id', 'PSJ-12')) ; // Category (should be only one) $email->getHeaders() ->add(new CategoryHeader('Integration Test')) ; }, ] ); } /** * Get the message content definition. */ public function content(): Content { return new Content( view: 'mail.welcome-email', with: ['name' => $this->name], ); } /** * Get the attachments for the message. * * @return array */ public function attachments(): array { return [ Attachment::fromPath('https://mailtrap.io/wp-content/uploads/2021/04/mailtrap-new-logo.svg') ->as('logo.svg') ->withMime('image/svg+xml'), ]; } /** * Get the message headers. */ public function headers(): Headers { return new Headers( 'custom-message-id@example.com', ['previous-message@example.com'], [ 'X-Custom-Header' => 'Custom Value', ], ); } } ``` -------------------------------- ### Install with Symfony HTTP client (recommended) Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Installs the Mailtrap PHP SDK for Laravel with the Symfony HTTP client, which is the recommended option. Requires Composer. ```bash # With symfony http client (recommend) composer require railsware/mailtrap-php symfony/http-client nyholm/psr7 symfony/mailer ``` -------------------------------- ### Run the send-template-mail CLI command Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Executes the Artisan command defined in the previous snippet to send the template email. ```bash php artisan send-template-mail ``` -------------------------------- ### Install Mailtrap PHP SDK with Symfony dependencies via Composer Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Run this command to install the Mailtrap PHP SDK along with required Symfony Mailer and HTTP client packages. ```bash composer require railsware/mailtrap-php symfony/http-client nyholm/psr7 symfony/mailer ``` -------------------------------- ### Run the batch-send-mail CLI command Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Executes the Artisan command defined in the previous snippet to send the batch emails. ```bash php artisan batch-send-mail ``` -------------------------------- ### Generate Mailable Class with Artisan Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Run this Artisan command to generate a new Mailable class named WelcomeMail. This is the first step before configuring the email. ```bash php artisan make:mail WelcomeMail ``` -------------------------------- ### Bulk Stream Client Initialization with isBulk: true Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Creates a Mailtrap client for bulk sending by setting isBulk: true. This is an optional variant of the standard sending client and requires the same API key. ```php $bulkClient = MailtrapClient::initSendingEmails(apiKey: $apiKey, isBulk: true); ``` -------------------------------- ### Sandbox vs Production Configuration with .env Variables Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Shows environment variables for toggling between Mailtrap Sandbox and Production. MAILTRAP_USE_SANDBOX controls the mode, and MAILTRAP_INBOX_ID is only needed for sandbox. Use separate API tokens for each environment. ```plaintext 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 for Sandbox vs Production Switching Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Initializes the Mailtrap client with sandbox/production switching based on environment variables. The inbox ID is only required for sandbox and is ignored for production. The email subject and sender address adapt to the mode. ```php from(new Address($isSandbox ? 'sandbox@example.com' : 'no-reply@your-domain.com')) ->to(new Address('recipient@example.com')) ->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)); ``` -------------------------------- ### Set default mailer, API key, and inbox ID for sandbox Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Environment variables for the sandbox (testing) environment. Requires MAILTRAP_API_KEY and MAILTRAP_INBOX_ID. ```bash MAIL_MAILER="mailtrap-sdk" MAILTRAP_HOST="sandbox.api.mailtrap.io" MAILTRAP_API_KEY="YOUR_API_KEY_HERE" MAILTRAP_INBOX_ID=1000001 ``` -------------------------------- ### Symfony services.yaml before upgrade (MailtrapTransportFactory) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the original service definition for Mailtrap\Bridge\Transport\MailtrapTransportFactory in config/services.yaml. Replace this with the new factory class. ```yaml ... # add more service definitions when explicit configuration is needed # please note that last definitions always *replace* previous ones Mailtrap\Bridge\Transport\MailtrapTransportFactory: tags: - { name: 'mailer.transport_factory' } ``` -------------------------------- ### Console Route to Send Welcome Mail Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Defines an Artisan command 'send-welcome-mail' that sends the WelcomeMail to a test recipient. Includes commented alternative to use a specific mailer 'mailtrap-sdk'. ```php # app/routes/console.php send(new WelcomeMail("Jon")); // Also, you can use specific mailer if your default mailer is not "mailtrap-sdk" but you want to use it for welcome mails // Mail::mailer('mailtrap-sdk')->to('testreceiver@gmail.com')->send(new WelcomeMail("Jon")); })->purpose('Send welcome mail'); ``` -------------------------------- ### General API: Before BC break (Accounts, Permissions, Users) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md Old way of accessing permissions and users endpoints where accountId is passed to the method. This is the 'Before' example for the BC break. ```php $mailtrap = new MailtrapClient(new Config(getenv('MAILTRAP_API_KEY'))); # no changes here $response = $mailtrap ->general() ->permissions() ->getResources(getenv('MAILTRAP_ACCOUNT_ID')); # <--- accountId here $response = $mailtrap ->general() ->users() ->getList(getenv('MAILTRAP_ACCOUNT_ID')); # <--- accountId here ``` -------------------------------- ### Sandbox API: Before BC break (Projects, Messages, Attachments, Inboxes) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md Old way of accessing inboxes endpoints where accountId is passed to the method. This is the 'Before' example for the BC break. ```php $mailtrap = new MailtrapClient(new Config(getenv('MAILTRAP_API_KEY'))); # no changes here $response = $mailtrap ->sandbox() ->inboxes() ->getList(getenv('MAILTRAP_ACCOUNT_ID')); # <--- accountId here ``` -------------------------------- ### Minimal Transactional Email Sending with MailtrapClient::initSendingEmails Source: https://github.com/railsware/mailtrap-php/blob/main/README.md Sends a single transactional email using only required parameters. Requires Composer autoloader and a Mailtrap API key from https://mailtrap.io/api-tokens. The response body is accessed via ResponseHelper::toArray(). ```php from(new Address('sender@example.com')) ->to(new Address('recipient@example.com')) ->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)); ``` -------------------------------- ### Welcome Email Blade Template Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Blade template for the welcome email, referenced by the Mailable's content view. Displays the recipient's name and a welcome message. ```php # resources/views/mail/welcome-email.blade.php Hey, {{$name}} and welcome here 😉
Funny Coder ``` -------------------------------- ### Clear Laravel configuration cache Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Clears the Laravel configuration cache so the new environment variables take effect. Run this after updating the .env file. ```bash php artisan config:clear ``` -------------------------------- ### Symfony services.yaml after upgrade (MailtrapSdkTransportFactory) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the updated service definition using Mailtrap\Bridge\Transport\MailtrapSdkTransportFactory. Use this to replace the old factory. ```yaml ... # add more service definitions when explicit configuration is needed # please note that last definitions always *replace* previous ones Mailtrap\Bridge\Transport\MailtrapSdkTransportFactory: tags: - { name: 'mailer.transport_factory' } ``` -------------------------------- ### Set default mailer and API key for sending Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Environment variables for the default sending transport. Sets MAIL_MAILER to 'mailtrap-sdk' and requires the MAILTRAP_API_KEY variable. ```bash MAIL_MAILER="mailtrap-sdk" MAILTRAP_HOST="send.api.mailtrap.io" MAILTRAP_API_KEY="YOUR_API_KEY_HERE" ``` -------------------------------- ### Set default mailer and API key for bulk sending Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Environment variables for bulk sending. Uses the bulk API host and requires the MAILTRAP_API_KEY variable. ```bash MAIL_MAILER="mailtrap-sdk" MAILTRAP_HOST="bulk.api.mailtrap.io" MAILTRAP_API_KEY="YOUR_API_KEY_HERE" ``` -------------------------------- ### General API: After BC break (Accounts, Permissions, Users) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md New way of accessing permissions and users endpoints where accountId is passed to the layer method. This is the 'After' example for the BC break. ```php // all permissions endpoints $response = $mailtrap ->general() ->permissions(getenv('MAILTRAP_ACCOUNT_ID')) # <--- accountId here ->getResources(); // all users endpoints $response = $mailtrap ->general() ->users(getenv('MAILTRAP_ACCOUNT_ID')) # <--- accountId here ->getList(); ``` -------------------------------- ### Laravel mail.php before upgrade (mailtrap transport) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the original mailtrap transport configuration in config/mail.php before upgrading to 3.0. Replace this with the new 'mailtrap-sdk' transport. ```php [ // start mailtrap transport 'mailtrap' => [ 'transport' => 'mailtrap' ], // end mailtrap transport ] ]; ``` -------------------------------- ### Laravel mailtrap-sdk config after upgrade (config/mailtrap-sdk.php) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the renamed configuration file with the 'mailtrap-sdk' key. Update the file name and key as shown to complete the upgrade. ```php # /config/mailtrap-sdk.php [ 'host' => env('MAILTRAP_HOST', 'send.api.mailtrap.io'), 'apiKey' => env('MAILTRAP_API_KEY'), 'inboxId' => env('MAILTRAP_INBOX_ID'), ], ]; ``` -------------------------------- ### Symfony MAILER_DSN before upgrade (mailtrap://) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the original MAILER_DSN values using the 'mailtrap' scheme. Replace these with the new 'mailtrap+sdk' scheme. ```bash MAILER_DSN=mailtrap://YOUR_API_KEY_HERE@default # or MAILER_DSN=mailtrap+api://YOUR_API_KEY_HERE@send.api.mailtrap.io ``` -------------------------------- ### Set MAIL_MAILER to mailtrap-sdk in .env Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Sets the default mailer transport to 'mailtrap-sdk' in the .env file, replacing the previous 'mailtrap' value. ```bash MAIL_MAILER="mailtrap-sdk" ``` -------------------------------- ### Symfony MAILER_DSN after upgrade (mailtrap+sdk://) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the updated MAILER_DSN values using the 'mailtrap+sdk' scheme. Use these to replace the old values. ```bash MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@default # or MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@send.api.mailtrap.io ``` -------------------------------- ### Sandbox API: After BC break (Projects, Messages, Attachments, Inboxes) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md New way of accessing inboxes endpoints where accountId is passed to the layer method. This is the 'After' example for the BC break. ```php // all sandbox(testing) endpoints: projects, messages, attachments, inboxes $response = $mailtrap ->sandbox() ->inboxes(getenv('MAILTRAP_ACCOUNT_ID')) # <--- accountId here ->getList(); ``` -------------------------------- ### Sandbox layer: Before BC break (inboxId in send) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md Old way of sending emails in Sandbox layer where inboxId is passed to the send method. This is the 'Before' example for the BC break. ```php $mailtrap = new MailtrapClient(new Config(getenv('MAILTRAP_API_KEY'))); $response = $mailtrap ->sandbox() ->emails() ->send($email, 1000001); # <--- inboxId here ``` -------------------------------- ### Email Template: Before BC break (using Email and headers) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md Old way of creating an email with template UUID and variables using Email class and headers. This is the 'Before' example for the Email Template class change. ```php $email = (new Email()) ->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401) ->replyTo(new Address('reply@YOUR-DOMAIN-HERE.com')) ->to(new Address('example@gmail.com', 'Jon')) ; // Template UUID and Variables $email->getHeaders() ->add(new TemplateUuidHeader('bfa432fd-0000-0000-0000-8493da283a69')) ->add(new TemplateVariableHeader('user_name', 'Jon Bush')) ->add(new TemplateVariableHeader('next_step_link', 'https://mailtrap.io/')) ->add(new TemplateVariableHeader('get_started_link', 'https://mailtrap.io/')) ->add(new TemplateVariableHeader('onboarding_video_link', 'some_video_link')) ; ``` -------------------------------- ### Add mailtrap-sdk transport to config/mail.php Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Adds the 'mailtrap-sdk' transport to the 'mailers' array in the Laravel mail configuration file. This is required to use the Mailtrap transport. ```php [ // start mailtrap transport 'mailtrap-sdk' => [ 'transport' => 'mailtrap-sdk' ], // end mailtrap transport ] ]; ``` -------------------------------- ### Laravel mailtrap config before upgrade (config/mailtrap.php) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-3.0.md Shows the original mailtrap configuration file with the 'mailtrap' key and environment variables. Rename this file and update the key as part of the upgrade. ```php # /config/mailtrap.php [ 'host' => env('MAILTRAP_HOST', 'send.api.mailtrap.io'), 'apiKey' => env('MAILTRAP_API_KEY'), 'inboxId' => env('MAILTRAP_INBOX_ID'), ], ]; ``` -------------------------------- ### Sandbox layer: After BC break (inboxId at client level) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md New way of sending emails in Sandbox layer using initSendingEmails or direct client with inboxId at client level. This is the 'After' example for the BC break. ```php # short method using `initSendingEmails` $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY'), #your API token from here https://mailtrap.io/api-tokens isSandbox: true, # required param for sandbox sending inboxId: getenv('MAILTRAP_INBOX_ID') # <--- inboxId here ); # or using the client directly (old variant) $mailtrap = (new MailtrapClient(new Config(getenv('MAILTRAP_API_KEY')))) ->sandbox() ->emails(getenv('MAILTRAP_INBOX_ID')); # <--- inboxId here $response = $mailtrap->send($email); ``` -------------------------------- ### Add mailtrap-sdk configuration to config/services.php Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Manually add these parameters to the config/services.php file when the Laravel service provider does not set them automatically, which can cause an IncompleteDsnException error on outdated Laravel versions. After adding, run the php artisan config:clear command. ```php 'mailtrap-sdk' => [ 'host' => env('MAILTRAP_HOST', 'send.api.mailtrap.io'), 'apiKey' => env('MAILTRAP_API_KEY'), 'inboxId' => env('MAILTRAP_INBOX_ID'), ], ``` -------------------------------- ### Email Template: After BC break (using MailtrapEmail) Source: https://github.com/railsware/mailtrap-php/blob/main/UPGRADE-2.0.md New way of creating an email with template UUID and variables using MailtrapEmail wrapper. This is the 'After' example for the Email Template class change. ```php use Mailtrap\Mime\MailtrapEmail; $email = (new MailtrapEmail()) # <--- new MIME class with template support ->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401) ->replyTo(new Address('reply@YOUR-DOMAIN-HERE.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' => 'some_video_link' ]) ; ``` -------------------------------- ### Add CLI command to send batch emails (batch-send-mail) Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Defines an Artisan command 'batch-send-mail' that sends batch emails using either the Transactional API or the Bulk API. The Bulk API is enabled by uncommenting the isBulk: true initialization and commenting out the transactional one. The base email is combined with recipient-specific emails via batchSend. ```php # app/routes/console.php from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // Use your domain installed in Mailtrap ->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')), ]; $mailtrap->batchSend($recipientEmails, $baseEmail); })->purpose('Send Batch Mail'); ``` -------------------------------- ### Send email from a Symfony controller using Mailtrap transport Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Example controller that sends an email using the Mailtrap transport. It builds a MailtrapEmail with custom variables and category, then sends it via the injected TransportInterface. ```php transport = $transport; } /** * @Route(name="send-email", path="/send-email", methods={"GET"}) * * @return JsonResponse */ public function sendEmail(): JsonResponse { $message = (new MailtrapEmail()) ->from('from@xample.com') ->to('to@xample.com') ->cc('cc@example.com') ->bcc('bcc@example.com') ->replyTo('fabien@example.com') ->priority(Email::PRIORITY_HIGH) ->subject('Test email') ->text('text') ->category('category') ->customVariables([ 'var1' => 'value1', 'var2' => 'value2' ]) ; $response = $this->transport->send($message); ``` -------------------------------- ### Add CLI command to send template email (send-template-mail) Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Laravel/README.md Defines an Artisan command 'send-template-mail' that uses MailtrapEmail with templateUuid and templateVariables. Do not set subject, text, HTML, or category when using a template, otherwise the API returns a validation error. Use your own domain in the from address to avoid a 401 error. ```php # app/routes/console.php from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401) ->replyTo(new Address('reply@YOUR-DOMAIN-HERE.com')) ->to(new Address('example@gmail.com', 'Jon')) // when using a template, you should not set a subject, text, HTML, category // otherwise there will be a validation error from the API side ->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 ]) ; MailtrapClient::initSendingEmails( apiKey: config('services.mailtrap-sdk.apiKey') // your API token from here https://mailtrap.io/api-tokens )->send($email); })->purpose('Send Template Mail'); ``` -------------------------------- ### Send batch email using MailtrapClient::batchSend Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Use this controller action to send batch emails via the native library. It shows both Transactional API and Bulk API initialization; uncomment the Bulk API line and comment out the transactional initialization to use bulk sending. The base email defines common fields, and recipient emails are created individually. The API key is read from the MAILTRAP_API_KEY environment variable. ```php /** * WARNING! To send Batch Email, you should use the native library and its methods * * @Route(name="send-batch-email", path="/send-batch-email", methods={"GET"}) * * @return JsonResponse */ public function sendBatchEmail(): JsonResponse { // Choose either Transactional API or Bulk API // For Transactional API $mailtrap = MailtrapClient::initSendingEmails( apiKey: getenv('MAILTRAP_API_KEY'), // Your API token from https://mailtrap.io/api-tokens ); // OR for Bulk API (uncomment the line below and comment out the transactional initialization) // $mailtrap = MailtrapClient::initSendingEmails( // apiKey: getenv('MAILTRAP_API_KEY'), // Your API token from https://mailtrap.io/api-tokens // isBulk: true // Enable bulk sending //); $baseEmail = (new MailtrapEmail()) ->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // Use your domain installed in Mailtrap ->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')), ]; $response = $mailtrap->batchSend($recipientEmails, $baseEmail); return JsonResponse::create(ResponseHelper::toArray($response)); } ``` -------------------------------- ### Send test email via Symfony CLI command Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Use this Symfony console command to send a test email. The mailer:test command is only available in Symfony 6.2 and later. ```bash php bin/console mailer:test to@example.com ``` -------------------------------- ### Configure MAILER_DSN for sandbox testing Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Set the MAILER_DSN to use the sandbox endpoint. Replace YOUR_API_KEY_HERE and set the correct inboxId. More info at the provided Mailtrap help link. ```bash MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@sandbox.api.mailtrap.io?inboxId=1000001 ``` -------------------------------- ### Configure MAILER_DSN for bulk sending Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Set the MAILER_DSN to use the bulk sending endpoint. Replace YOUR_API_KEY_HERE with your API key. More info at the provided Mailtrap help link. ```bash MAILER_DSN=mailtrap+sdk://YOUR_API_KEY_HERE@bulk.api.mailtrap.io ``` -------------------------------- ### Send template email using MailtrapEmail and MailtrapClient Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Use this controller action to send an email via a Mailtrap Email Template. It requires the native library methods because mail transport validation does not allow sending without 'html' or 'text'. Set your own domain in the from address to avoid a 401 error, and do not set subject, text, HTML, or category when using a template to prevent API validation errors. The API key is read from the MAILTRAP_API_KEY environment variable. ```php /** * WARNING! To send using Mailtrap Email Template, you should use the native library and its methods, * as mail transport validation does not allow you to send emails without ‘html’ or ‘text’ * * @Route(name="send-template-email", path="/send-template-email", methods={"GET"}) * * @return JsonResponse */ public function sendTemplateEmail(): JsonResponse { $email = (new MailtrapEmail()) ->from(new Address('example@YOUR-DOMAIN-HERE.com', 'Mailtrap Test')) // <--- you should use your domain here that you installed in the mailtrap.io admin area (otherwise you will get 401) ->replyTo(new Address('reply@YOUR-DOMAIN-HERE.com')) ->to(new Address('example@gmail.com', 'Jon')) // when using a template, you should not set a subject, text, HTML, category // otherwise there will be a validation error from the API side ->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 = MailtrapClient::initSendingEmails( apiKey: env('MAILTRAP_API_KEY') // your API token from here https://mailtrap.io/api-tokens )->send($email); return JsonResponse::create(ResponseHelper::toArray($response)); } ``` -------------------------------- ### Register MailtrapSdkTransportFactory in config/services.yaml Source: https://github.com/railsware/mailtrap-php/blob/main/src/Bridge/Symfony/README.md Add this service definition to your Symfony services.yaml to register the Mailtrap transport factory. The tag 'mailer.transport_factory' is required. ```yaml ... # add more service definitions when explicit configuration is needed # please note that last definitions always *replace* previous ones Mailtrap\Bridge\Transport\MailtrapSdkTransportFactory: tags: - { name: 'mailer.transport_factory' } ```