Repository navigation
Transport (Mail, SMS)
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 —
MailerInterfacefor mail,TransportInterfacefor 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
| Feature | 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 | ✅ | ✅ |
┌────────────────────┐
│ 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 │ │ │
└─────────────────┘ └──────────────────────┘
-
Manager — the entry point.
MailManagerandSMSManagerresolve the correct transport and orchestrate events, logging, and (de)serialization. -
Message — a value object describing what to send (
MailMessage, SMSMessage). -
Response — a value object describing the outcome (
MailResponse, SMSResponse). -
Transport — the actual delivery mechanism. Implements
MailerInterfaceorTransportInterface. -
Registry —
TransportRegistryinstantiates transports from config (SMS only; mail transports are built inline inMailManager). -
Job — a queued wrapper for async sends (
SendMailJob,SendSmsJob).
The SMS driver for Africa's Talking requires:
composer require africastalking/africastalkingMail via SMTP requires:
composer require phpmailer/phpmailer<?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.
<?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,
],
],
],
];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();$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);$mailer->send($message, 'phpmailer');$transport = $mailer->getTransport('phpmailer');
$transport->send($message);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');
}
);$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. |
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,
MailManagerwill auto-generate theSendMailJobclass viaQueueJobGeneratorif it doesn't exist.
Job payload shape:
[
'message' => $message->jsonSerialize(),
'transport' => 'phpmailer',
]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.
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();
}$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).
$message = Message::fromArray([
'to' => '+254712345678',
'body' => 'Hello!', // 'body' aliases 'text'
'from' => 'MYAPP',
]);The AbstractTransport base class wraps every send with:
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.
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.
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]).
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).
| 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:
SendSmsJobemitssms.sendingin addition to the above.
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
TransportRegistryconstructor currently registersafricastalkingby default. Add your driver viaregister()or extend the class.
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)
);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.
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 }(fromSendSmsJob) -
sms.send→{ message, transport } -
sms.sent→{ response, transport } -
sms.send_failed→{ response | exception, transport }
MailMessage implements JsonSerializable. Persist and restore with:
$payload = json_encode($message); // → JSON
$message = MailMessage::fromArray($json); // ← MailMessageThis is how queued email jobs round-trip message state.
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',
]);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');| 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. |
| 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. |
| 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. |
| 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. |
// 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(): ?stringMail 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).
-
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. - Set retry policies thoughtfully. Only retry idempotent failures. Sending a duplicate OTP because a timeout was actually a success is worse than failing.
- Tune idempotency TTL. The 60s default is fine for OTPs; extend it for transactional SMS that users may trigger twice.
-
Watch circuit breaker thresholds. In high-throughput systems, lower
failureThreshold(e.g. 3) so you fail fast before provider rate limits cascade. -
Use named transports. Add a
'failover'transport pointing to a secondary provider for critical mail; select it manually whenphpmailercircuit trips (for mail you'll need to add circuit breaker support yourself — it's not built in). -
Render templates outside the loop. When sending bulk mail, render the HTML once and reuse
$message->html($html, $text)where data is static. -
Log responses.
MailResponse::getMessageId()and SMSgetMessageId()are your provider-side receipts; persist them for support investigations. -
Never log secrets.
PhpMailerTransportonly logs subject/recipients; extend the same discipline to custom transports. -
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. -
Write integration tests against a fake transport. Implement a
MailerInterface/TransportInterfacethat records messages, then assert on the recorded collection. This avoids hitting real SMTP or SMS providers in CI.
Machinjiri Docs
- Home
- Learn
- Build
-
Tutorials
- Routing
- Controllers and Middleware
- Views and Templates
- Database ORM
- Eloquent Database ORM
- Errors and Exceptions
- Forms and Validation
- Http
- Events and Logging
- Services and DI
- Security
- Authentication
- Caching
- File System
- Date and Time
- Debugging
- Queue and Jobs
- Task Scheduling
- Transport (Mail, SMS)
- LDAP
- Notifications
- Webhooks
- UUID Generations
- Terminal
- Helper Function
- Reference