Laravel
Send from Laravel through Charchy Send — a small client on the Http facade, sign-in codes that expire, receipts from queued jobs, a mail transport for your Mailables and notifications, and a verified webhook route.
For Laravel 11, 12 and 13: a few small files on the Http facade.
1. Configuration
CHARCHY_SEND_KEY=chy_test_…
CHARCHY_SEND_FROM="My App <no-reply@myapp.com>"
CHARCHY_WEBHOOK_SECRET=whsec_…'charchy_send' => [
'key' => env('CHARCHY_SEND_KEY'),
'from' => env('CHARCHY_SEND_FROM'),
'webhook_secret' => env('CHARCHY_WEBHOOK_SECRET'),
],Read them with config('services.charchy_send.key') — env() returns null
outside config files once the config is cached.
2. The client
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
use Throwable;
class CharchySend
{
/**
* Send one email and return its id ("em_…").
*
* @param array<string, mixed> $email The API's fields: to, subject, html and/or text; optional from, cc, bcc, reply_to, tags, attachments, scheduled_at, expires_at
*
* @throws RequestException refused (402, 403, 422…), or still failing after the retries
* @throws ConnectionException unreachable after the retries
*/
public function send(array $email, string $idempotencyKey): string
{
return Http::withToken(config('services.charchy_send.key'))
->withHeaders(['Idempotency-Key' => $idempotencyKey])
->acceptJson()
->timeout(30)
->retry(3, $this->retryDelay(...), $this->shouldRetry(...))
->post('https://api.charchy.krd/v1/emails', [
'from' => config('services.charchy_send.from'),
...$email,
])
->json('id');
}
/** Network errors, 5xx, a short 429 and 409 idempotency_in_flight. Never 402 or another 4xx. */
private function shouldRetry(Throwable $exception): bool
{
if ($exception instanceof ConnectionException) {
return true;
}
if (! $exception instanceof RequestException) {
return false;
}
$response = $exception->response;
return $response->serverError()
|| ($response->status() === 429 && (int) $response->header('Retry-After') <= 10)
|| $response->json('error.code') === 'idempotency_in_flight';
}
/** Retry-After when the API sends one, else 1 s, then 2 s. */
private function retryDelay(int $attempt, Throwable $exception): int
{
$retryAfter = $exception instanceof RequestException
? (int) $exception->response->header('Retry-After')
: 0;
return max($retryAfter, $attempt) * 1000;
}
}retry()'s third argument decides what is retried: network errors,5xx, a429that clears within 10 seconds, and409 idempotency_in_flight. Everything else —402 insufficient_balance,403 domain_not_verified,422 validation_error— throws aRequestExceptionat once; read$exception->response->json('error.code').- Every retry sends the same
Idempotency-Key, so it can never send twice.
3. Sign-in codes that expire
Send codes directly, not from the queue — the person is waiting:
use App\Services\CharchySend;
app(CharchySend::class)->send([
'to' => [$user->email],
'subject' => "Your sign-in code: {$code}",
'text' => "Your code is {$code}. It expires in 10 minutes.",
'expires_at' => now()->addMinutes(10)->toIso8601String(), // dropped and refunded if it can't leave in time
'tags' => ['type' => 'signin_code'],
], idempotencyKey: "signin-code/{$codeRow->id}");4. Receipts from a queued job
<?php
namespace App\Jobs;
use App\Models\Order;
use App\Services\CharchySend;
use Illuminate\Contracts\Queue\ShouldQueueAfterCommit;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Http\Client\RequestException;
class SendReceipt implements ShouldQueueAfterCommit
{
use Queueable;
public $tries = 5;
public $backoff = [10, 60, 300, 900];
public function __construct(public Order $order) {}
public function handle(CharchySend $charchy): void
{
try {
$emailId = $charchy->send([
'to' => [$this->order->user->email],
'subject' => "Receipt for order #{$this->order->id}",
'html' => view('mail.receipt', ['order' => $this->order])->render(),
'tags' => ['type' => 'receipt'],
], idempotencyKey: "receipt/{$this->order->id}");
} catch (RequestException $exception) {
// A refusal (402, 403, 422…) won't change on a retry; a 429 or 5xx may.
if ($exception->response->clientError() && $exception->response->status() !== 429) {
$this->fail($exception);
return;
}
throw $exception;
}
$this->order->update(['charchy_email_id' => $emailId]);
}
}SendReceipt::dispatch($order); // inside a DB::transaction too: it waits for the commitShouldQueueAfterCommit: nothing is sent for an order whose transaction rolled back.- The key comes from the order, not the attempt: a job retried after a timeout gets the first email's id back instead of sending a second one.
- A refusal fails the job at once; an outage or a
429goes back on the queue with$backoff.
5. Every Mailable and notification: a mail transport
Keep your Mailables, notifications and Laravel's own password-reset and verification emails — a custom transport sends them all through the API.
<?php
namespace App\Mail;
use App\Services\CharchySend;
use Symfony\Component\Mailer\Header\MetadataHeader;
use Symfony\Component\Mailer\SentMessage;
use Symfony\Component\Mailer\Transport\AbstractTransport;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\MessageConverter;
use Symfony\Component\Mime\Part\DataPart;
class CharchySendTransport extends AbstractTransport
{
/** Headers a Mailable sets to steer the send. Read here, never forwarded. */
public const IDEMPOTENCY_KEY_HEADER = 'X-Charchy-Idempotency-Key';
public const EXPIRES_AT_HEADER = 'X-Charchy-Expires-At';
public function __construct(private CharchySend $client)
{
parent::__construct();
}
protected function doSend(SentMessage $message): void
{
$email = MessageConverter::toEmail($message->getOriginalMessage());
$headers = $email->getHeaders();
$addresses = fn (array $list): array => array_map(fn (Address $address) => $address->toString(), $list);
// The Envelope's `metadata` become tags: metadata: ['type' => 'order_shipped'].
$tags = [];
foreach ($headers->all() as $header) {
if ($header instanceof MetadataHeader) {
$tags[$header->getKey()] = $header->getValue();
}
}
$body = array_filter([
'from' => $email->getFrom()[0]->toString(),
'to' => $addresses($email->getTo()),
'cc' => $addresses($email->getCc()),
'bcc' => $addresses($email->getBcc()),
'reply_to' => $addresses($email->getReplyTo()),
'subject' => $email->getSubject(),
'html' => $email->getHtmlBody(),
'text' => $email->getTextBody(),
'tags' => $tags,
'expires_at' => $headers->get(self::EXPIRES_AT_HEADER)?->getBodyAsString(),
'attachments' => array_map(fn (DataPart $part) => [
'filename' => $part->getFilename(),
'content' => base64_encode($part->getBody()),
'content_type' => $part->getContentType(),
], $email->getAttachments()),
]);
// Without the header: a hash of the email, so a retried queued job
// sends nothing twice — and the same email to the same person within
// 24 hours is sent once.
$idempotencyKey = $headers->get(self::IDEMPOTENCY_KEY_HEADER)?->getBodyAsString()
?? 'laravel/'.hash('sha256', json_encode($body));
$message->setMessageId($this->client->send($body, $idempotencyKey));
}
public function __toString(): string
{
return 'charchy';
}
}use App\Mail\CharchySendTransport;
use App\Services\CharchySend;
use Illuminate\Support\Facades\Mail;
public function boot(): void
{
Mail::extend('charchy', fn () => new CharchySendTransport($this->app->make(CharchySend::class)));
}'mailers' => [
'charchy' => [
'transport' => 'charchy',
],
// …
],MAIL_MAILER=charchy
MAIL_FROM_ADDRESS=no-reply@myapp.com
MAIL_FROM_NAME="My App"A Mailable steers the send with an Envelope's metadata (sent as tags) and
the two headers the transport reads:
<?php
namespace App\Mail;
use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;
use Illuminate\Queue\SerializesModels;
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
public function __construct(public Order $order) {}
public function envelope(): Envelope
{
return new Envelope(
subject: "Order #{$this->order->id} has shipped",
metadata: ['type' => 'order_shipped'], // sent as tags
);
}
public function headers(): Headers
{
return new Headers(text: [
CharchySendTransport::IDEMPOTENCY_KEY_HEADER => "order-shipped/{$this->order->id}",
]);
}
public function content(): Content
{
return new Content(view: 'mail.order-shipped');
}
}| Set on the Mailable | Sent as |
|---|---|
metadata: ['type' => 'order_shipped'] | tags |
X-Charchy-Idempotency-Key header | Idempotency-Key |
X-Charchy-Expires-At header (ISO 8601) | expires_at |
Mail::to($user)->send(...) returns the sent message; its
getMessageId() is the em_… id. Attachments are sent (up to 3, 3 MB in
all); images embedded with $message->embed() are not — use a
hosted image instead.
6. Webhooks
composer require standard-webhooks/standard-webhooksuse App\Http\Controllers\CharchyWebhookController;
Route::post('/webhooks/charchy', CharchyWebhookController::class);Charchy Send can't send a CSRF token, so take the route out of CSRF protection:
->withMiddleware(function (Middleware $middleware): void {
$middleware->preventRequestForgery(except: [
'webhooks/charchy',
]);
})On Laravel 11 and 12 the method is validateCsrfTokens(except: [...])
(Laravel 13 still accepts that name).
<?php
namespace App\Http\Controllers;
use App\Jobs\HandleCharchyEvent;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use StandardWebhooks\Exception\WebhookVerificationException;
use StandardWebhooks\Webhook;
class CharchyWebhookController
{
public function __invoke(Request $request): Response
{
// The whole "whsec_…" secret; the library drops the prefix itself.
$webhook = new Webhook(config('services.charchy_send.webhook_secret'));
try {
$event = $webhook->verify($request->getContent(), [ // the raw body
'webhook-id' => $request->header('webhook-id'),
'webhook-timestamp' => $request->header('webhook-timestamp'),
'webhook-signature' => $request->header('webhook-signature'),
]);
} catch (WebhookVerificationException) {
return response('Invalid signature', 400);
}
HandleCharchyEvent::dispatch($event); // answer now, work later
return response()->noContent();
}
}<?php
namespace App\Jobs;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class HandleCharchyEvent implements ShouldQueue
{
use Queueable;
/** @param array<string, mixed> $event The verified payload: id, type, created_at, data */
public function __construct(public array $event) {}
public function handle(): void
{
$data = $this->event['data'];
match ($this->event['type']) {
// Idempotent, so a redelivered event changes nothing.
'email.bounced', 'email.complained' => User::where('email', $data['recipient'])
->update(['email_undeliverable_at' => now()]),
default => null,
};
}
}The controller answers 204 at once and the job does the work. Events can
arrive twice and out of order: keep the handling idempotent, or record
$event['id'] and skip repeats. In the dashboard, under Webhooks, add
https://myapp.com/webhooks/charchy. Without the package:
plain HMAC as middleware.
7. Try it
With a test key, from php artisan tinker:
Mail::raw('It works.', fn ($message) => $message->to('delivered@sim.charchy.krd')->subject('Hello'));It shows on the dashboard's Emails page a moment later. Send to
bounced@sim.charchy.krd and the email.bounced webhook marks the user. In
tests, Http::fake(['api.charchy.krd/*' => Http::response(['id' => 'em_test', 'status' => 'queued'])])
keeps every call local.