PHP code example of mosaiqo / mailer-php

1. Go to this page and download the library: Download mosaiqo/mailer-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mosaiqo / mailer-php example snippets


'mailers' => [
    // ...existing mailers...
    'mailer' => [
        'transport' => 'mailer',
    ],
],

use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;

// A Mailable through the transport (MAIL_MAILER=mailer)
Mail::to('[email protected]')->send(new WelcomeMail($user));

// A plain message
Mail::raw('Hello world', fn ($m) => $m->to('[email protected]')->subject('Hi'));

use Mailer\Sdk\Laravel\Facades\Mailer;

Mailer::send()->email([
    'to' => '[email protected]',
    'template' => 'welcome',           // template slug from mailer-app
    'variables' => ['first_name' => 'Jane'],
]);

// ...or fully inline content
Mailer::send()->email([
    'to' => '[email protected]',
    'subject' => 'Welcome aboard',
    'body' => '<p>Hi {{ contact.first_name }}!</p>',
    'text' => 'Hi!',
]);

use Mailer\Sdk\MailerClient;

$client = new MailerClient(
    baseUrl: 'https://app.example.com/api/v1',
    token: 'your-project-api-key',
);

// Send a single transactional email (inline content)
$sent = $client->send()->email([
    'to' => '[email protected]',
    'subject' => 'Welcome aboard',
    'body' => '<p>Hi {{ contact.first_name }}!</p>',
    'text' => 'Hi!',
    'variables' => ['plan' => 'pro'],
]);

echo $sent->id;      // "11111111-2222-..."
echo $sent->status;  // "queued"

// Or send using a stored template by slug
$client->send()->email([
    'to' => '[email protected]',
    'template' => 'welcome',
    'variables' => ['first_name' => 'Jane'],
]);

// Attachments: max 10 files, 10 MB decoded per file and per send total
// (over-total → 422 with code `attachments_too_large`); executable filename
// extensions are rejected. Single sends only — /send/batch rejects them.
$client->send()->email([
    'to' => '[email protected]',
    'template' => 'invoice',
    'attachments' => [
        [
            'filename' => 'invoice.pdf',
            'content_type' => 'application/pdf',
            'content' => base64_encode($pdfBytes), // standard base64, no data: prefix
        ],
    ],
]);

$result = $client->send()->batch([
    ['to' => '[email protected]', 'template' => 'welcome'],
    ['to' => '[email protected]', 'subject' => 'Hi', 'body' => '<p>Hello</p>'],
]);

echo $result->queued; // 2
echo $result->failed; // 0

foreach ($result->messages as $item) {
    // $item->index, $item->status (queued|suppressed|failed), $item->id, $item->code, $item->error
}

$result = $client->notifications()->send([
    'to' => '[email protected]',
    'title' => 'Your order shipped',
    'body' => 'Tracking #1234 is on its way.',
    'channels' => ['in_app', 'push'], // optional; defaults to ['in_app']
    'action_url' => 'https://app.example.com/orders/1234',
    'variables' => ['first_name' => 'Jane'],
]);

if (! $result->anyQueued()) {
    // Nothing could be delivered — inspect the per-channel outcomes below.
}

foreach ($result->messages as $channel) {
    // $channel->channel, $channel->id, $channel->status, $channel->errorCode
}

$push = $result->channel('push');
if ($push && ! $push->queued()) {
    echo $push->errorCode; // e.g. push_provider_not_configured
}

$result = $client->push()->register('[email protected]', 'fcm-device-token', 'android');
echo $result->registered; // true
echo $result->devices;    // number of push devices now on the contact

$removed = $client->push()->remove('[email protected]', 'fcm-device-token');
echo $removed->removed;    // true, or false if the contact had no such token

$client->send()->email(
    ['to' => '[email protected]', 'template' => 'welcome'],
    idempotencyKey: 'order-1234-welcome',
);

$client->send()->batch($messages, idempotencyKey: 'nightly-digest-2026-06-12');

// Track an event
$client->send()->track('order.placed', '[email protected]', ['total' => 4200]);

// Subscribe a contact (double opt-in aware)
$client->send()->subscribe([
    'email' => '[email protected]',
    'first_name' => 'Jane',
    'lists' => [7],
    'tags' => ['newsletter'],
]);

// Contacts
$page = $client->contacts()->list(['status' => 'subscribed', 'per_page' => 50]);
$contact = $client->contacts()->get('[email protected]');
$client->contacts()->update('[email protected]', ['first_name' => 'Janet']);
$client->contacts()->tags('[email protected]', add: ['vip'], remove: ['trial']);
$client->contacts()->cancelAutomationRuns('[email protected]', automation: 12);
$client->contacts()->delete('[email protected]'); // GDPR erase

// Lists
$lists = $client->lists()->list();
$list = $client->lists()->create('Newsletter', 'Weekly digest');
$client->lists()->attachContact($list->id, '[email protected]');
$client->lists()->detachContact($list->id, '[email protected]');

// Tags (flat array)
$tags = $client->tags()->list();

// Templates
$templates = $client->templates()->list();
$template = $client->templates()->create([
    'name' => 'Welcome',
    'slug' => 'welcome',
    'subject' => 'Welcome!',
    'body_html' => '<p>Hi</p>',
]);
$client->templates()->putVariant('welcome', 'es', [
    'subject' => '¡Bienvenido!',
    'body_html' => '<p>Hola</p>',
]);

// Messages (read-only)
$messages = $client->messages()->list(['status' => 'delivered']);
$message = $client->messages()->get('11111111-2222-...');
foreach ($message->events as $event) {
    // $event->type, $event->payload, $event->occurredAt
}

// Campaigns (read-only by design — no send/schedule from the SDK)
$campaigns = $client->campaigns()->list(['per_page' => 50]);
$campaign = $client->campaigns()->get(7);
// $campaign->stats is a populated CampaignStats only on get():
echo $campaign->stats->openRate ?? 0; // rates are null when undefined

foreach ($client->contacts()->cursor(['status' => 'subscribed']) as $contact) {
    echo $contact->email.PHP_EOL;
}

// Available cursors (each yields the same DTOs as the matching list()):
$client->contacts()->cursor($query);           // Contact
$client->messages()->cursor($query);           // Message
$client->campaigns()->cursor($query);          // Campaign
$client->lists()->cursor($query);              // ContactList
$client->lists()->contactsCursor($id, $query); // Contact
$client->templates()->cursor($query);          // Template

use Illuminate\Support\LazyCollection;

LazyCollection::make($client->contacts()->cursor())
    ->filter(fn ($contact) => $contact->status === 'subscribed')
    ->each(fn ($contact) => /* ... */);

$client = new MailerClient(
    baseUrl: 'https://app.example.com/api/v1',
    token: 'your-project-api-key',
    httpClient: null,
    options: [
        'retries' => 2,            // max retry attempts
        'retry_base_delay' => 200, // ms, exponential backoff base
        'retry_max_delay' => 5000, // ms, backoff cap
        'retry_on_status' => range(500, 599), // statuses to retry (429 always retried)
        'timeout' => 30,           // Guzzle request timeout (seconds)
        'connect_timeout' => 10,   // Guzzle connect timeout (seconds)
    ],
);

use Mailer\Sdk\Exception\ValidationException;
use Mailer\Sdk\Exception\RateLimitException;
use Mailer\Sdk\Exception\MailerException;

try {
    $client->send()->email(['to' => '[email protected]', 'template' => 'welcome']);
} catch (ValidationException $e) {
    if ($e->getErrorCode() === 'recipient_suppressed') {
        // address is on the suppression list — skip it
    }
    $fieldErrors = $e->errors(); // ['to' => ['The to field is 

// 1. Send through the code under test (sandbox token configured).
$client->send()->email(['to' => '[email protected]', 'template' => 'welcome']);

// 2. The sandbox captures every send — read it back like an inbox.
$message = $client->messages()->list(['status' => 'queued'])->data[0];

// 3. Drive the pipeline: simulate provider/engagement events on that message.
$client->sandbox()->simulate($message->uuid, SandboxResource::EVENT_DELIVERED);
$client->sandbox()->simulate($message->uuid, SandboxResource::EVENT_OPEN);
$client->sandbox()->simulate($message->uuid, SandboxResource::EVENT_CLICK, linkIndex: 0);

// 4. Assert on the resulting state.
$refreshed = $client->messages()->get($message->uuid);
// $refreshed->events now contains delivered / opened / clicked

use Mailer\Sdk\Resources\SandboxResource;

// Available events (plain strings work too):
SandboxResource::EVENT_DELIVERED;   // 'delivered'
SandboxResource::EVENT_HARD_BOUNCE; // 'hard_bounce'
SandboxResource::EVENT_SOFT_BOUNCE; // 'soft_bounce'
SandboxResource::EVENT_COMPLAINT;   // 'complaint'
SandboxResource::EVENT_OPEN;        // 'open'
SandboxResource::EVENT_CLICK;       // 'click' — pass linkIndex or url
SandboxResource::EVENT_READ;        // 'read'

use Mailer\Sdk\MailerClient;

public function __construct(private MailerClient $mailer) {}

// ...
$this->mailer->send()->email([...]);

'mailers' => [
    // ...
    'mailer' => [
        'transport' => 'mailer',
    ],
],

// Plain message
Mail::raw('Hello world', fn ($m) => $m->to('[email protected]')->subject('Hi'));

// A Mailable
Mail::to('[email protected]')->send(new WelcomeMail($user));

use Mailer\Sdk\Laravel\Mail\MailerHeaders;

class WelcomeMail extends Mailable
{
    public function build()
    {
        return $this
            ->subject('Welcome') // ignored when a template header is present
            ->withSymfonyMessage(function ($message) {
                $headers = $message->getHeaders();
                $headers->addTextHeader(MailerHeaders::TEMPLATE, 'welcome');
                $headers->addTextHeader(
                    MailerHeaders::VARIABLES,
                    json_encode(['first_name' => 'Jane']),
                );
            });
    }
}

use Mailer\Sdk\Laravel\Mail\MailerMessage;

public function toMailer($notifiable): MailerMessage
{
    return (new MailerMessage)
        ->subject('Your order shipped')
        ->html('<p>It is on the way.</p>')
        ->text('It is on the way.');
}

return (new MailerMessage)
    ->template('order-shipped')
    ->variables(['name' => $notifiable->name]);

use Illuminate\Notifications\Notification;
use Mailer\Sdk\Laravel\Mail\MailerMessage;

class OrderShipped extends Notification
{
    public function via($notifiable): array
    {
        return ['mailer'];
    }

    public function toMailer($notifiable): MailerMessage
    {
        return (new MailerMessage)
            ->subject('Your order shipped')
            ->html('<p>It is on the way.</p>');
        // Or a stored template:
        // return (new MailerMessage)->template('order-shipped')->variables(['name' => $notifiable->name]);
    }
}

use Mailer\Sdk\Laravel\Facades\Mailer;

Mailer::contacts()->list();
Mailer::send()->email([
    'to' => '[email protected]',
    'subject' => 'Hello',
    'body' => '<p>Hi</p>',
]);
bash
composer 
json
{
    "repositories": [
        { "type": "path", "url": "sdk/php" }
    ],
    "
bash
composer 
bash
composer 
bash
php artisan vendor:publish --tag=mailer-sdk-config