Skip to content

Transport (Mail, SMS)

Precious Lyson edited this page Nov 13, 2026 · 2 revisions

The Transport System provides a single, consistent API for sending messages across different channels (Email, SMS). It abstracts away provider-specific details and gives you:

  • A unified interface — MailerInterface for mail, TransportInterface for SMS
  • Multiple transports — SMTP via PHPMailer, Africa's Talking SMS, and extensible drivers
  • Reliability primitives — automatic retries with exponential backoff, circuit breakers, rate limiting, and idempotency
  • Async delivery — dispatch sends to a background queue with SendMailJob / SendSmsJob
  • Observability — structured logging and lifecycle events for every send

Features

Feature Mail SMS
Multiple transports/drivers ✅ ✅
Queue support ✅ ✅
Retries with backoff ✅ ✅
Circuit breaker — ✅
Rate limiting — ✅
Idempotency — ✅
Template rendering ✅ —
Attachments / Embedded images ✅ —
Event hooks ✅ ✅
Structured logging ✅ ✅
Config-driven registration ✅ ✅

Architecture

                         ┌────────────────────┐
                         │   MailManager      │
                         │  (facade / driver) │
                         └─────────┬──────────┘
                                   │
                 ┌─────────────────┼──────────────────┐
                 │                 │                  │
        ┌────────▼──────┐  ┌───────▼───────┐  ┌──────▼────────┐
        │ MailMessage   │  │ MailResponse  │  │ SendMailJob   │
        └───────────────┘  └───────────────┘  └───────────────┘
                                   │
                         ┌─────────▼────────────┐
                         │ MailerInterface      │
                         └─────────┬────────────┘
                                   │
                      ┌────────────┴─────────────┐
                      │                          │
             ┌────────▼────────┐        ┌────────▼────────┐
             │PhpMailerTransport│       │ (Your transport)│
             └─────────────────┘        └─────────────────┘


                         ┌────────────────────┐
                         │    SMSManager      │
                         │  (facade / driver) │
                         └─────────┬──────────┘
                                   │
                      ┌────────────┴──────────────┐
                      │                           │
             ┌────────▼────────┐         ┌────────▼────────┐
             │TransportRegistry│         │ TransportInterface│
             └────────┬────────┘         └────────┬─────────┘
                      │                           │
                      │                  ┌────────▼─────────┐
                      │                  │ AbstractTransport │  ◄── Retries, circuit,
                      │                  │  (base class)     │      rate limit,
                      │                  └────────┬─────────┘      idempotency
                      │                           │
             ┌────────▼────────┐         ┌────────▼─────────────┐
             │AfricasTalking   │         │ (Your transport)     │
             │Transport        │         │                      │
             └─────────────────┘         └──────────────────────┘

Key concepts

  • Manager — the entry point. MailManager and SMSManager resolve the correct transport and orchestrate events, logging, and (de)serialization.
  • Message — a value object describing what to send (MailMessage, SMS Message).
  • Response — a value object describing the outcome (MailResponse, SMS Response).
  • Transport — the actual delivery mechanism. Implements MailerInterface or TransportInterface.
  • Registry — TransportRegistry instantiates transports from config (SMS only; mail transports are built inline in MailManager).
  • Job — a queued wrapper for async sends (SendMailJob, SendSmsJob).

Installation

The SMS driver for Africa's Talking requires:

composer require africastalking/africastalking

Mail via SMTP requires:

composer require phpmailer/phpmailer

Configuration

Mail — config/mail.php

<?php

return [
    'default' => 'phpmailer',

    'transports' => [
        'phpmailer' => [
            'transport'  => 'phpmailer',
            'host'       => env('MAIL_HOST', 'smtp.example.com'),
            'username'   => env('MAIL_USERNAME'),
            'password'   => env('MAIL_PASSWORD'),
            'port'       => (int) env('MAIL_PORT', 587),
            'encryption' => env('MAIL_ENCRYPTION', 'tls'),
            'from_email' => env('MAIL_FROM_ADDRESS', 'no-reply@example.com'),
            'from_name'  => env('MAIL_FROM_NAME', 'My App'),
            'debug'      => false,
        ],
    ],
];

Required keys for phpmailer: host, username, password, port, encryption, from_email.

SMS — config/sms.php

<?php

return [
    'default' => 'africastalking',

    // Force all sends to go through the queue
    'async' => env('SMS_ASYNC', false),

    'transports' => [
        'africastalking' => [
            'driver'   => 'africastalking',
            'username' => env('AT_USERNAME'),
            'api_key'  => env('AT_API_KEY'),

            'retry' => [
                'max_attempts'   => 3,
                'base_delay_ms'  => 1000,
                'backoff_factor' => 2.0,
                'jitter_factor'  => 0.1,
            ],
        ],
    ],
];

Mail Transport

Mail Quick Start

use Mlangeni\Machinjiri\Core\Container;
use Mlangeni\Machinjiri\Core\Transport\Mail\MailManager;
use Mlangeni\Machinjiri\Core\Transport\Mail\MailMessage;

$mailer = new MailManager($container);

$message = (new MailMessage())
    ->from('noreply@myapp.com', 'My App')
    ->to('jane@example.com', 'Jane Doe')
    ->subject('Welcome aboard!')
    ->html('<h1>Hello Jane!</h1><p>Thanks for signing up.</p>');

$response = $mailer->send($message);

echo $response->getMessageId();

Sending Mail

Fluent message building

$message = (new MailMessage())
    ->from('noreply@myapp.com', 'My App')
    ->to('alice@example.com', 'Alice')
    ->to('bob@example.com', 'Bob')
    ->cc('manager@example.com')
    ->bcc('audit@example.com')
    ->replyTo('support@example.com')
    ->subject('Monthly Report')
    ->html('<p>Your report is attached.</p>', 'Your report is attached.')
    ->priority(1);

Using a named transport

$mailer->send($message, 'phpmailer');

Getting a transport directly

$transport = $mailer->getTransport('phpmailer');
$transport->send($message);

Mail Templates

Templates are plain PHP files that receive your data as extracted variables.

1. Implement a renderer

use Mlangeni\Machinjiri\Core\Transport\Mail\PhpTemplateRenderer;

$renderer = new PhpTemplateRenderer(__DIR__ . '/views/mail');

2. Create templates

views/mail/welcome.html.php:

<h1>Welcome, <?= htmlspecialchars($name) ?>!</h1>
<p>Click <a href="<?= $activationUrl ?>">here</a> to activate your account.</p>

views/mail/welcome.text.php:

Welcome, <?= $name ?>!

Activate your account: <?= $activationUrl ?>

3. Send with sendTemplate()

$mailer = new MailManager($container, renderer: $renderer);

$response = $mailer->sendTemplate(
    'welcome',
    ['name' => 'Jane', 'activationUrl' => 'https://myapp.com/activate/abc123'],
    function (MailMessage $m) {
        $m->from('noreply@myapp.com', 'My App')
          ->to('jane@example.com')
          ->subject('Activate your account');
    }
);

Attachments & Embedded Images

$message = (new MailMessage())
    ->from('billing@myapp.com', 'Billing')
    ->to('customer@example.com')
    ->subject('Your Invoice')
    ->html('<img src="cid:logo"><p>Invoice attached.</p>')
    ->attachFile('/var/app/invoices/INV-001.pdf', 'invoice.pdf', 'application/pdf')
    ->attachContent($pdfBlob, 'summary.pdf', 'application/pdf')
    ->embedImage('/var/app/assets/logo.png', 'logo');
Method Description
attachFile($path, $name?, $contentType?) Attach a file from disk.
attachContent($content, $name, $contentType?) Attach raw bytes.
embedImage($path, $cid) Inline image referenced by cid:<id> in HTML.

Queuing Emails

Async sending requires a JobDispatcherInterface bound in the container.

$mailer = new MailManager(
    $container,
    dispatcher: $container->make(JobDispatcherInterface::class)
);

$jobId = $mailer->queue(
    $message,
    transportName: 'phpmailer',
    jobOptions: ['max_attempts' => 3, 'queue' => 'emails']
);

On first use, MailManager will auto-generate the SendMailJob class via QueueJobGenerator if it doesn't exist.

Job payload shape:

[
    'message'   => $message->jsonSerialize(),
    'transport' => 'phpmailer',
]

Custom Mail Transports

Implement MailerInterface:

use Mlangeni\Machinjiri\Core\Transport\Mail\MailerInterface;
use Mlangeni\Machinjiri\Core\Transport\Mail\MailMessage;
use Mlangeni\Machinjiri\Core\Transport\Mail\MailResponse;

class SesTransport implements MailerInterface
{
    public function __construct(private array $config, private $logger) {}

    public function send(MailMessage $message): MailResponse
    {
        // ... send via AWS SES ...
        return new MailResponse($sesMessageId, 'ses', ['region' => 'us-east-1']);
    }
}

Then extend MailManager::registerTransport() to recognize your type. Or bypass the manager entirely and use your transport directly.


SMS Transport

SMS Quick Start

use Mlangeni\Machinjiri\Core\Transport\SMS\SMSManager;
use Mlangeni\Machinjiri\Core\Transport\SMS\Message;

$sms = SMSManager::fromConfig($config['sms'], $container);

$message = Message::builder()
    ->to('+254712345678')
    ->text('Your verification code is 123456')
    ->from('MYAPP')
    ->build();

$response = $sms->send($message);

if ($response->isSuccess()) {
    echo "Sent: " . $response->getMessageId();
} else {
    echo "Failed: " . $response->getError();
}

Sending SMS

Fluent builder

$message = Message::builder()
    ->to('+254712345678')
    ->text('Hello!')
    ->from('MYAPP')
    ->encoding('GSM7')
    ->validityPeriod(3600)         // seconds
    ->withDeliveryReceipt(true)
    ->withOption('custom_key', 'value')
    ->build();

Phone numbers are normalized automatically (non-numeric/+ characters are stripped).

From an array

$message = Message::fromArray([
    'to'   => '+254712345678',
    'body' => 'Hello!',          // 'body' aliases 'text'
    'from' => 'MYAPP',
]);

SMS Reliability Features

The AbstractTransport base class wraps every send with:

1. Circuit breaker

After N consecutive failures (failureThreshold, default 5), the circuit opens for timeoutSeconds (default 60). Calls fail fast with SMSException::transportError(...) until it closes. On the next success the circuit resets.

2. Rate limiter (token bucket)

RateLimiter($cache, $identifier, $capacity, $refillRate) — allows up to capacity sends, refilled at refillRate tokens per second. Exceeding it throws SMSException::transportError("Rate limit exceeded...").

The default SMS registry uses 10 tokens / 2 per second.

3. Idempotency

Every message gets a key derived from md5(transport + to + text + from):

// Returns true if already sent within the TTL window (default 60s)
$store->isProcessed($key);

// Atomic lock to prevent concurrent duplicate sends
$store->lock($key);
$store->markProcessed($key);
$store->unlock($key);

Duplicate sends return a Response(true, 'duplicate', null, ['idempotent' => true]).

4. Retries with exponential backoff + jitter

RetryPolicy($maxAttempts, $baseDelayMs, $backoffFactor, $jitterFactor):

delay(n) = base_delay_ms * backoff_factor^(n-1)
jitter   = delay * jitter_factor * rand(-1, 1)
sleep    = max(50ms, delay + jitter)

Retryability is decided by your transport via isRetryableFailure(Response) and isRetryableException(\Throwable).

Lifecycle events

Event When
sms.send Just before the first attempt
sms.sent After a successful send
sms.send_failed After a permanent failure (or exhausted retries)

Note: SendSmsJob emits sms.sending in addition to the above.

Custom SMS Transports

Extend AbstractTransport and implement three methods:

use Mlangeni\Machinjiri\Core\Transport\SMS\{AbstractTransport, Message, Response};

class TwilioTransport extends AbstractTransport
{
    public function getName(): string
    {
        return 'twilio';
    }

    protected function doSend(Message $message): Response
    {
        try {
            $result = $this->client->messages->create(
                $message->getTo(),
                ['from' => $message->getFrom(), 'body' => $message->getText()]
            );
            return new Response(true, $result->sid);
        } catch (\Twilio\Exceptions\TwilioException $e) {
            return new Response(false, null, $e->getMessage());
        }
    }

    protected function isRetryableFailure(Response $response): bool
    {
        // e.g. retry on 5xx but not on 4xx
        return str_contains((string) $response->getError(), 'rate limit');
    }

    protected function isRetryableException(\Throwable $e): bool
    {
        return $e instanceof \Twilio\Exceptions\RestException && $e->getCode() >= 500;
    }
}

Register it:

$registry = new TransportRegistry($logger, $container);
$registry->register('twilio', TwilioTransport::class);

// Or in your config: 'driver' => 'twilio'

The TransportRegistry constructor currently registers africastalking by default. Add your driver via register() or extend the class.

How TransportRegistry::make() wires dependencies

When you pass a transport config, the registry constructs:

new $class(
    $container,
    new RetryPolicy(
        $config['retry']['max_attempts'] ?? 3,
        $config['retry']['base_delay_ms'] ?? 1000,
        $config['retry']['backoff_factor'] ?? 2.0,
        $config['retry']['jitter_factor'] ?? 0.1,
    ),
    new CircuitBreaker($cache, $driver),
    new IdempotencyStore($cache),
    new RateLimiter($cache, $driver, 10, 2)
);

Async SMS

Set 'async' => true in config, or pass $async = true to send():

$response = $sms->send($message, async: true);

if ($response->getRaw()['queued'] ?? false) {
    echo "Queued as job: " . $response->getMessageId();
}

Requires queue.dispatcher bound in the container. The job is dispatched to the sms queue with maxRetries => 1 (retries are handled by the transport's RetryPolicy).

⚠️ SMSManager::fromConfig() calls $container->resolve('queue.dispatcher') eagerly. If you only need sync sends and haven't registered a dispatcher, wire the constructor manually or ensure a default binding exists.


Advanced Topics

Event hooks

Both managers trigger lifecycle events via EventListener:

Mail:

  • mail.sending → { message, transport }
  • mail.sent → { message, response, transport }
  • mail.failed → { message, exception, transport }
  • mail.queued → { message, job_id, transport }

SMS:

  • sms.sending → { to, message, transport } (from SendSmsJob)
  • sms.send → { message, transport }
  • sms.sent → { response, transport }
  • sms.send_failed → { response | exception, transport }

Serialization

MailMessage implements JsonSerializable. Persist and restore with:

$payload = json_encode($message);          // → JSON
$message = MailMessage::fromArray($json);  // ← MailMessage

This is how queued email jobs round-trip message state.

Logging

Every manager and transport logs via Logger (PSR-3-compatible interface in this framework):

$this->logger->info('Sending email', [
    'subject' => $message->getSubject(),
    'to'      => $message->getTo(),
    'transport' => 'default',
]);

Config loading

MailManager looks for config/mail.php under $container->coreConfig. If you prefer, inject a config array in the constructor instead:

$mailer = new MailManager($container, config: require __DIR__ . '/config/mail.php');

API Reference

MailManager

Method Returns Description
__construct(Container $app, ?array $config, ?Logger, ?EventListener, ?TemplateRendererInterface, ?JobDispatcherInterface) — Build transports from config.
send(MailMessage $message, ?string $transportName = null): MailResponse MailResponse Send synchronously.
sendTemplate(string $templateName, array $data, callable $callback, ?string $transportName = null): MailResponse MailResponse Render .html.php / .text.php templates, then send.
queue(MailMessage $message, ?string $transportName = null, array $jobOptions = []): string string (job id) Queue for async delivery.
getTransport(string $name): MailerInterface MailerInterface Fetch a transport instance.

MailMessage (fluent)

Method Notes
from($email, $name = null) Single sender.
to($email, $name = null) Appends recipient.
toMany(array $recipients) Array of strings or ['email'=>..., 'name'=>...].
cc($email, $name = null) / bcc(...) / replyTo(...) As expected.
subject($subject) —
html($html, $text = null) Auto-generates text from HTML if $text omitted.
text($text) Plain-text only.
attachFile(...) / attachContent(...) / embedImage(...) Attachments & inline images.
header($key, $value) / priority($level) Custom headers, priority 1–5.
jsonSerialize() / toArray() / fromArray() Serialization.

SMSManager

Method Returns Description
SMSManager::fromConfig(array $config, Container $container): self SMSManager Factory from config.
send(Message $message, bool $async = false): Response Response Send sync or async.
addTransport(TransportInterface $transport): void — Register a transport instance.

SMS Message builder

Method Notes
to(string $phone) Normalizes number.
text(string $text) Required.
from(?string $sender) Sender ID.
encoding(string) / validityPeriod(int) / withDeliveryReceipt(bool) / withOption($k, $v) Optional flags.
build(): Message Validates to + text, returns a clone.

Response (SMS) / MailResponse

// SMS
$response->isSuccess(): bool
$response->getMessageId(): ?string
$response->getError(): ?string
$response->getRaw(): array

// Mail
$response->getMessageId(): string
$response->getTransport(): string
$response->getMetadata(): array
$response->getRawResponse(): ?string

Troubleshooting

Mail configuration file not found at: .../config/mail.php Create the file or pass a $config array to the MailManager constructor.

Default mail transport 'X' not registered Check the default key in config/mail.php matches a key in transports.

Missing PHPMailer config: password All of host, username, password, port, encryption, from_email are required for PhpMailerTransport.

Template renderer not set You called sendTemplate() without providing a TemplateRendererInterface to MailManager.

Job dispatcher not configured Bind a JobDispatcherInterface in the container before calling queue().

SMS Circuit open for transport ... The transport has had too many consecutive failures. Check your provider status, then wait for timeoutSeconds or reset via your cache.

SMS Rate limit exceeded Slow down sends or increase capacity/refillRate in RateLimiter.

SMS returns duplicate Idempotency detected an identical message (to + text + from) within the TTL window (default 60s). Adjust the IdempotencyStore TTL if this is too aggressive.

SendMailJob was generated but class still not found Ensure your autoloader picks up the newly generated job file (may require composer dump-autoload).


Best Practices

  1. Use the queue for non-critical sends. Welcome emails, marketing SMS, and reports belong in queue()/send($msg, async: true) — not in the request/response cycle.
  2. Set retry policies thoughtfully. Only retry idempotent failures. Sending a duplicate OTP because a timeout was actually a success is worse than failing.
  3. Tune idempotency TTL. The 60s default is fine for OTPs; extend it for transactional SMS that users may trigger twice.
  4. Watch circuit breaker thresholds. In high-throughput systems, lower failureThreshold (e.g. 3) so you fail fast before provider rate limits cascade.
  5. Use named transports. Add a 'failover' transport pointing to a secondary provider for critical mail; select it manually when phpmailer circuit trips (for mail you'll need to add circuit breaker support yourself — it's not built in).
  6. Render templates outside the loop. When sending bulk mail, render the HTML once and reuse $message->html($html, $text) where data is static.
  7. Log responses. MailResponse::getMessageId() and SMS getMessageId() are your provider-side receipts; persist them for support investigations.
  8. Never log secrets. PhpMailerTransport only logs subject/recipients; extend the same discipline to custom transports.
  9. Version your templates. Prefix with v1_ or store under a version path so you can roll back without breaking queued jobs that reference old template names.
  10. Write integration tests against a fake transport. Implement a MailerInterface/TransportInterface that records messages, then assert on the recorded collection. This avoids hitting real SMTP or SMS providers in CI.

Clone this wiki locally