Skip to content
Browse the docs

Frameworks and agents · Published 2026-09-29 · Updated 2026-11-10 · AgentiSend

Send email from Laravel

Send email from Laravel with the AgentiSend mail driver, or with a controller method that posts one shipping notice and returns the id or the fix.

To send email from Laravel, set the mailer to the AgentiSend driver so Mail posts JSON to POST /emails, or put one method on a controller that posts the same JSON with PHP streams. The driver is the agentisend/laravel package. The method below checks the address, sends with an idempotency key derived from the recipient, and returns the message id, or the refusal's code and fix. It is run by the test suite against a local AgentiSend server. The run calls the method; it does not boot the framework.

Install

The mail driver:

composer require agentisend/laravel
driver-install

The controller method on this page uses PHP streams and needs no extra package. Point a route at it:

Route::post('/send', [OrderController::class, 'send']);

Read the JSON body in the framework and pass email and note into send.

The mail driver

Mail::raw and a Mailable both use the driver once the mailer is named agentisend. The transport posts the message to POST /emails, stores the returned id as the Symfony message id, and throws when the API refuses. The exception's fix is the API's fix.

'mailers' => [
    'agentisend' => [
        'transport' => 'agentisend',
    ],
],
driver
MAIL_MAILER=agentisend
AGENTISEND_API_KEY=as_your_key
mailer
use Illuminate\Support\Facades\Mail;

Mail::raw('Your order shipped', function ($message) {
    $message->from(config('mail.from.address'))
        ->to('ada@example.com')
        ->replyTo('reply@example.com')
        ->subject('Shipped');
});
send

An attachment on the Mailable is posted as base64 content, with its filename and media type. A header you add, including List-Unsubscribe, is posted in headers. replyTo is posted as reply_to. Look the id up with GET /emails/{id}. Create the key with POST /api-keys.

Symfony Mailer, without Laravel, uses the same transport. Tag AgentiSend\Laravel\AgentiSendTransportFactory with mailer.transport_factory and set the DSN to agentisend+api://as_your_key@default.

The controller method further down does not use the driver. It posts with PHP streams, and the suite runs that file.

Environment

VariableRequiredWhat it is
AGENTISEND_API_KEYyesA key with sending_access.
MAIL_FROMyesThe From address, on a domain you have verified.
AGENTISEND_BASE_URLnoDefaults to https://api.agentisend.com.

The route

<?php
/**
 * Laravel — the method a controller route calls.
 *
 * The mail driver is the agentisend/laravel package, on this guide. The method
 * below is the other way: it posts JSON to POST /emails with PHP streams, the
 * same call a queued job would make. The framework is not booted here; the
 * method is the one the route holds.
 *
 * AGENTISEND_API_KEY, MAIL_FROM, and optionally AGENTISEND_BASE_URL.
 * Run: php send.php
 */

/** Enough to refuse an obvious typo here; the API checks the address properly. */
function laravel_address_ok(string $email): bool
{
    return preg_match('/^[^@\s]+@[^@\s]+\.[^@\s]+$/', $email) === 1;
}

final class OrderController
{
    /**
     * POST /send  {"email": "ada@example.com", "note": "packed"}
     *
     * @param array{email?: string, note?: string} $input
     * @return array{status: int, body: array<string, mixed>}
     */
    public function send(array $input): array
    {
        $email = trim((string) ($input['email'] ?? ''));
        $note = (string) ($input['note'] ?? '');
        if (!laravel_address_ok($email)) {
            return [
                'status' => 400,
                'body' => ['error' => 'email must be one address, like you@example.com'],
            ];
        }

        $from = getenv('MAIL_FROM');
        if ($from === false || $from === '') {
            throw new RuntimeException('Set MAIL_FROM to an address on a domain you have verified.');
        }
        $base = getenv('AGENTISEND_BASE_URL');
        if ($base === false || $base === '') {
            $base = 'https://api.agentisend.com';
        }
        $key = getenv('AGENTISEND_API_KEY') ?: '';
        $payload = json_encode([
            'from' => $from,
            'to' => $email,
            'subject' => 'Your order shipped',
            'text' => 'Shipping note: ' . $note,
        ], JSON_THROW_ON_ERROR);

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => implode("\r\n", [
                    'authorization: Bearer ' . $key,
                    'content-type: application/json',
                    'accept: application/json',
                    // The order's recipient, not the moment the job ran.
                    'idempotency-key: shipped/' . $email,
                ]),
                'content' => $payload,
                'ignore_errors' => true,
                'timeout' => 30,
            ],
        ]);
        $raw = file_get_contents(rtrim((string) $base, '/') . '/emails', false, $context);
        if ($raw === false) {
            throw new RuntimeException('POST /emails failed before a response');
        }
        $status = 0;
        if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $match) === 1) {
            $status = (int) $match[1];
        }
        /** @var array<string, mixed> $parsed */
        $parsed = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        if ($status >= 400) {
            $error = is_array($parsed['error'] ?? null) ? $parsed['error'] : [];
            return ['status' => $status, 'body' => ['code' => $error['code'] ?? null, 'fix' => $error['fix'] ?? null]];
        }
        return ['status' => $status, 'body' => ['id' => $parsed['id'] ?? null]];
    }
}

/**
 * @param array{status: int, body: array<string, mixed>} $result
 */
function laravel_emit(string $step, array $result): void
{
    echo json_encode(['step' => $step, 'status' => $result['status']] + $result['body'], JSON_THROW_ON_ERROR), "\n";
}

if (PHP_SAPI === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
    $controller = new OrderController();
    laravel_emit('send', $controller->send(['email' => 'laravel@example.com', 'note' => 'first']));
    laravel_emit('retry', $controller->send(['email' => 'laravel@example.com', 'note' => 'first']));
    laravel_emit('invalid', $controller->send(['email' => 'not-an-address', 'note' => 'first']));
    laravel_emit('refused', $controller->send(['email' => 'laravel@example.com', 'note' => 'second']));
}
examples/laravel/send.php, run by the test suite against a local AgentiSend server

Try it

php send.php

The file prints one JSON object per step: the notice, the same request again, a malformed address answered before any request, and a changed note under the same key.

What comes back when it goes wrong

Every refused request carries code, message, fix and docs_url. The method returns code and fix with the API's status, which the route renders as its response. The error catalogue lists every code.

Next

Examples

Prompt for your coding agent

1. Install

npm install agentisend

2. Environment

AGENTISEND_API_KEY
MAIL_FROM
AGENTISEND_BASE_URL=https://api.agentisend.com

3. Send call

<?php
/**
 * Laravel — the method a controller route calls.
 *
 * The mail driver is the agentisend/laravel package, on this guide. The method
 * below is the other way: it posts JSON to POST /emails with PHP streams, the
 * same call a queued job would make. The framework is not booted here; the
 * method is the one the route holds.
 *
 * AGENTISEND_API_KEY, MAIL_FROM, and optionally AGENTISEND_BASE_URL.
 * Run: php send.php
 */

/** Enough to refuse an obvious typo here; the API checks the address properly. */
function laravel_address_ok(string $email): bool
{
    return preg_match('/^[^@\s]+@[^@\s]+\.[^@\s]+$/', $email) === 1;
}

final class OrderController
{
    /**
     * POST /send  {"email": "ada@example.com", "note": "packed"}
     *
     * @param array{email?: string, note?: string} $input
     * @return array{status: int, body: array<string, mixed>}
     */
    public function send(array $input): array
    {
        $email = trim((string) ($input['email'] ?? ''));
        $note = (string) ($input['note'] ?? '');
        if (!laravel_address_ok($email)) {
            return [
                'status' => 400,
                'body' => ['error' => 'email must be one address, like you@example.com'],
            ];
        }

        $from = getenv('MAIL_FROM');
        if ($from === false || $from === '') {
            throw new RuntimeException('Set MAIL_FROM to an address on a domain you have verified.');
        }
        $base = getenv('AGENTISEND_BASE_URL');
        if ($base === false || $base === '') {
            $base = 'https://api.agentisend.com';
        }
        $key = getenv('AGENTISEND_API_KEY') ?: '';
        $payload = json_encode([
            'from' => $from,
            'to' => $email,
            'subject' => 'Your order shipped',
            'text' => 'Shipping note: ' . $note,
        ], JSON_THROW_ON_ERROR);

        $context = stream_context_create([
            'http' => [
                'method' => 'POST',
                'header' => implode("\r\n", [
                    'authorization: Bearer ' . $key,
                    'content-type: application/json',
                    'accept: application/json',
                    // The order's recipient, not the moment the job ran.
                    'idempotency-key: shipped/' . $email,
                ]),
                'content' => $payload,
                'ignore_errors' => true,
                'timeout' => 30,
            ],
        ]);
        $raw = file_get_contents(rtrim((string) $base, '/') . '/emails', false, $context);
        if ($raw === false) {
            throw new RuntimeException('POST /emails failed before a response');
        }
        $status = 0;
        if (isset($http_response_header[0]) && preg_match('/\s(\d{3})\s/', $http_response_header[0], $match) === 1) {
            $status = (int) $match[1];
        }
        /** @var array<string, mixed> $parsed */
        $parsed = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
        if ($status >= 400) {
            $error = is_array($parsed['error'] ?? null) ? $parsed['error'] : [];
            return ['status' => $status, 'body' => ['code' => $error['code'] ?? null, 'fix' => $error['fix'] ?? null]];
        }
        return ['status' => $status, 'body' => ['id' => $parsed['id'] ?? null]];
    }
}

/**
 * @param array{status: int, body: array<string, mixed>} $result
 */
function laravel_emit(string $step, array $result): void
{
    echo json_encode(['step' => $step, 'status' => $result['status']] + $result['body'], JSON_THROW_ON_ERROR), "\n";
}

if (PHP_SAPI === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
    $controller = new OrderController();
    laravel_emit('send', $controller->send(['email' => 'laravel@example.com', 'note' => 'first']));
    laravel_emit('retry', $controller->send(['email' => 'laravel@example.com', 'note' => 'first']));
    laravel_emit('invalid', $controller->send(['email' => 'not-an-address', 'note' => 'first']));
    laravel_emit('refused', $controller->send(['email' => 'laravel@example.com', 'note' => 'second']));
}

4. Parameter reference

POST /emails
attachments array<object>
bcc any
cc any
expires_at string
from string
headers object
html string
replyTo any
reply_to any
scheduledAt string
scheduled_at string
subject string
tags any
template object
template_id string
template_values object
text string
timezone string
to any required
topicId string
topic_id string
Idempotency-Key header
Resend-Idempotency-Key header

5. Rules

Read the API key on the server. Do not send it to the browser.
Send an Idempotency-Key derived from the thing being done, not from the clock.
A refusal is JSON with code, message, fix and docs_url. Follow fix.

6. Verify

GET /emails/{id}
The id is the one the send call returned.