PHP Email API in Laravel: Send, Receive and Store Email with Queued Jobs and a Signed Webhook

Integrate a PHP email API with Laravel: a service provider, sends from a controller and a queued job, a signed webhook route without CSRF, and feature tests.

By · · 18 min read

A Laravel controller in PHP that creates an address and sends an email with the Mailcycle PHP SDK

A PHP email API is easy to call from a script. Fitting one into a Laravel app takes a few more decisions: where the client is built, which settings go in .env, what runs in the request and what goes on the queue, how a webhook route gets past CSRF without opening a hole, and how to test all of it without sending real mail.

This tutorial answers those with one small app. Each team in it gets its own email address for receipts. Team members forward invoices and taxi receipts to that address, Laravel files every email and its PDF under the team, and a queued job replies in the same thread to confirm. It uses the Mailcycle PHP SDK, installed with Composer, and every piece of code below was run against a live account on Laravel 13.

For the basics on their own, two shorter posts cover them: How to send email from PHP for HTML, attachments and error codes, and How to receive email in PHP for reading an inbox, attachments and waitFor(). This post is about the Laravel structure around those calls.

Quick answer: a PHP email API call in a Laravel controller

Type-hint a service that wraps the client, make an address, and send from it:

public function store(Team $team, Mailbox $mailbox): RedirectResponse
{
    $address = $mailbox->createAddress(Str::slug($team->name), "Receipts for {$team->name}");

    $mailbox->send(new Outgoing(
        from: $address->emailAddress,
        to: $team->owner_email,
        subject: "Your receipts address for {$team->name}",
        text: "Forward receipts and invoices to {$address->emailAddress}.\n",
    ));

    return back()->with('status', "Forward receipts to {$address->emailAddress}");
}

Mailbox is a twenty-line class from step 2 that the service container builds once. The address it creates receives mail as well as sending it, which is what the rest of the tutorial uses: replies and forwards to that address come back to Laravel on a signed webhook.

Flow: a Laravel controller creates a team address and emails it to the owner, the owner forwards a receipt, a signed webhook brings it to Laravel, which stores it and replies from a queued job
Laravel creates an address per team, the team forwards receipts to it, and a signed webhook brings each one back to be stored and answered.

What the Laravel receipts inbox does

Piece File Job
Settings .env, config/services.php API key, recovery phrase, webhook secret
Service provider app/Providers/MailcycleServiceProvider.php Builds one client for the whole app
Wrapper app/Services/Mailbox.php The four calls the app makes, easy to mock
Controller app/Http/Controllers/TeamInboxController.php Creates the team address and sends the welcome email
Webhook route routes/web.php, bootstrap/app.php Takes message.received, outside CSRF
Middleware app/Http/Middleware/VerifyMailcycleSignature.php Refuses anything not signed by Mailcycle
Jobs app/Jobs/ProcessInboundEmail.php, AcknowledgeReceipt.php Stores the mail, then replies in the thread
Tests tests/Feature/ Signed and forged deliveries, storage, duplicates

The same shape fits support inboxes, order replies, or any feature where your users email something to your app.

Plans and settings you need

The receiving half runs on the Operator plan, which includes API keys, webhooks and 250 addresses. The two sends in this app use an API key, and sending from an API key comes with Scale ($19/month), which also brings 1,000 addresses, 250 sends a day and up to 10 of your own domains. The pricing page lists every plan.

You need PHP 8.3 or later, which is Laravel 13’s minimum (the SDK itself runs on 8.1 and up), with the sodium extension that most PHP builds include. Run php -m | grep sodium to check.

Step 1: Install the PHP SDK with Composer

The package is served from Mailcycle’s own Composer repository. Add it to the project, then require the package:

composer config repositories.mailcycle composer https://mailcycle.email/php
composer require mailcycle/mailcycle

The SDK has no dependencies beyond PHP extensions, so it adds nothing else to composer.lock.

Put the settings in .env and config/services.php

Add four lines to .env:

MAILCYCLE_API_KEY=mak_...
MAILCYCLE_PHRASE="your twelve recovery words"
MAILCYCLE_WEBHOOK_SECRET=
MAILCYCLE_TIMEOUT=30

Then add a mailcycle block to config/services.php, next to the services already there:

<?php

return [

    'mailcycle' => [
        'key' => env('MAILCYCLE_API_KEY'),
        'phrase' => env('MAILCYCLE_PHRASE'),
        'webhook_secret' => env('MAILCYCLE_WEBHOOK_SECRET'),
        'timeout' => env('MAILCYCLE_TIMEOUT', 30),
    ],

];

Laravel’s own advice applies here: once you run php artisan config:cache, env() only returns real environment variables, so call it from config files and read config('services.mailcycle.key') everywhere else.

Where each value comes from

  • The recovery phrase is your account. You see the twelve words when you make the account at https://app.mailcycle.email/operator/signup, and nothing can recover them, so store them in your secrets manager as well as .env.
  • The API key comes from the API page in the app, under Keys. It starts with mak_ and is shown once.
  • The webhook secret is shown once when you add the webhook in step 6. Leave it empty until then.

The app needs the phrase as well as the key because it creates addresses that receive mail and opens the mail that arrives. An address’s public key is derived from the phrase, and mail is encrypted the moment it arrives, so the client opens each message in your PHP process with keys from those twelve words.

Step 2: Bind the email API client in a Laravel service provider

Generate a provider for the client. make:provider adds it to bootstrap/providers.php for you:

php artisan make:provider MailcycleServiceProvider
<?php

namespace App\Providers;

use App\Services\Mailbox;
use Illuminate\Support\ServiceProvider;
use Mailcycle\Mailcycle;
use Mailcycle\Options;
use RuntimeException;

class MailcycleServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->singleton(Mailcycle::class, function (): Mailcycle {
            $config = config('services.mailcycle');

            if (blank($config['key'] ?? null) || blank($config['phrase'] ?? null)) {
                throw new RuntimeException('Set MAILCYCLE_API_KEY and MAILCYCLE_PHRASE in .env');
            }

            return Mailcycle::withApiKey(
                $config['key'],
                $config['phrase'],
                new Options(timeoutSeconds: (int) $config['timeout']),
            );
        });

        $this->app->singleton(Mailbox::class);
    }
}

The Mailcycle singleton is built the first time something asks for it, so a request that never touches email never builds it. withApiKey() derives the account keys from the phrase and checks that the phrase belongs to the key’s account once, at that moment. A missing value fails loudly with a clear message, rather than as a 401 on the first send.

A Mailbox class the app depends on

Controllers and jobs in this app never type-hint Mailcycle directly. They ask for Mailbox, a plain class with the four calls the app needs:

<?php

namespace App\Services;

use Mailcycle\Mailcycle;
use Mailcycle\Models\Address;
use Mailcycle\Models\Message;
use Mailcycle\Models\SendResult;
use Mailcycle\NewAddress;
use Mailcycle\Outgoing;

class Mailbox
{
    public function __construct(private Mailcycle $mailcycle)
    {
    }

    public function createAddress(string $prefix, string $label): Address
    {
        return $this->mailcycle->addresses()->create(new NewAddress(prefix: $prefix, label: $label));
    }

    public function send(Outgoing $outgoing): SendResult
    {
        return $this->mailcycle->messages()->send($outgoing);
    }

    public function get(string $messageId): Message
    {
        return $this->mailcycle->messages()->get($messageId);
    }

    public function attachment(Message $message, int $index): string
    {
        return $this->mailcycle->messages()->attachment($message, $index);
    }
}

There are two reasons for the extra class. Mailcycle is a final class, so tests replace Mailbox instead, with one line: $this->mock(Mailbox::class). And the app’s whole email surface is now in one file, which makes it easy to see what the integration does. $this->app->singleton(Mailbox::class) with no closure lets the container build it and inject the client.

What a singleton means under queue workers

php artisan queue:work boots the app once and keeps it in memory, so a worker builds the client on its first email job and reuses it for every job after that. Key derivation happens once per worker process, not once per job. The client keeps no per-request state, so it is also safe to share across requests under Laravel Octane. The flip side of a long-lived worker: after you change the key or the phrase, run php artisan queue:restart so workers pick up the new config.

Step 3: Migrations and models for teams and inbound email

Two tables. Teams carry the id and the email of their Mailcycle address:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('teams', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('owner_email');
            $table->string('inbox_address_id')->nullable()->unique();
            $table->string('inbox_email')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('teams');
    }
};

Inbound email rows are keyed by the Mailcycle message id, with a unique index. That index is what makes webhook retries harmless in step 7:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('inbound_emails', function (Blueprint $table) {
            $table->id();
            $table->foreignId('team_id')->constrained()->cascadeOnDelete();
            $table->string('mailcycle_message_id')->unique();
            $table->string('from_address');
            $table->string('subject');
            $table->text('body');
            $table->json('files');
            $table->timestamp('received_at');
            $table->timestamp('acknowledged_at')->nullable();
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('inbound_emails');
    }
};

The models are short:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Team extends Model
{
    protected $fillable = ['name', 'owner_email', 'inbox_address_id', 'inbox_email'];

    public function inboundEmails(): HasMany
    {
        return $this->hasMany(InboundEmail::class);
    }
}
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class InboundEmail extends Model
{
    protected $fillable = [
        'team_id', 'mailcycle_message_id', 'from_address', 'subject',
        'body', 'files', 'received_at', 'acknowledged_at',
    ];

    protected function casts(): array
    {
        return [
            'files' => 'array',
            'received_at' => 'datetime',
            'acknowledged_at' => 'datetime',
        ];
    }

    public function team(): BelongsTo
    {
        return $this->belongsTo(Team::class);
    }
}

Run php artisan migrate. The files column holds storage paths, and the array cast turns it into a PHP array both ways.

Step 4: Send email from a Laravel controller

The controller creates the team’s address the first time it is asked, saves it on the team, and emails the address to the team owner:

<?php

namespace App\Http\Controllers;

use App\Models\Team;
use App\Services\Mailbox;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Str;
use Mailcycle\Outgoing;

class TeamInboxController extends Controller
{
    public function store(Team $team, Mailbox $mailbox): RedirectResponse
    {
        if ($team->inbox_email !== null) {
            return back()->with('status', "Forward receipts to {$team->inbox_email}");
        }

        $address = $mailbox->createAddress(Str::slug($team->name), "Receipts for {$team->name}");

        $team->update([
            'inbox_address_id' => $address->id,
            'inbox_email' => $address->emailAddress,
        ]);

        $mailbox->send(new Outgoing(
            from: $address->emailAddress,
            to: $team->owner_email,
            subject: "Your receipts address for {$team->name}",
            text: "Forward receipts and invoices to {$address->emailAddress}.\n\n"
                ."We file each one under {$team->name} and reply to confirm. "
                ."To try it now, reply to this email with a PDF attached.\n",
            fromName: config('app.name'),
        ));

        return back()->with('status', "Forward receipts to {$address->emailAddress}");
    }
}

A few details worth knowing:

  • The prefix becomes the start of the address, and Mailcycle adds a random ending, so “Acme Studio” gets an address such as acme-studio-gftb@ on one of your plan’s domains. On Scale you can also choose the whole name before the @, or use your own domain.
  • The label is a private note shown in the Mailcycle app next to the address. The client seals it before it leaves your server.
  • The send comes from the new address. When the owner replies to the welcome email, the reply goes to the team’s address, so the first test of the inbox is one click away.
  • The early return makes the action safe to call twice: a second click shows the address it already has.

Add the route to routes/web.php. It sits with your other dashboard routes, so it keeps CSRF protection and whatever auth middleware your app uses for team settings:

<?php

use App\Http\Controllers\MailcycleWebhookController;
use App\Http\Controllers\TeamInboxController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::post('/teams/{team}/inbox', [TeamInboxController::class, 'store'])
    ->name('teams.inbox.store');

Route::post('/webhooks/mailcycle', MailcycleWebhookController::class)
    ->middleware('mailcycle.signature')
    ->name('webhooks.mailcycle');

The webhook route is in the same file, because it belongs to the app, and the next steps deal with CSRF for it.

Step 5: Send email from a queued job and reply in the thread

When a receipt arrives, the app confirms it from a queued job. The job runs after the webhook has already answered, it has its own retries, and a slow send never holds up anything else:

<?php

namespace App\Jobs;

use App\Models\InboundEmail;
use App\Services\Mailbox;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Mailcycle\Exception\ApiException;
use Mailcycle\Outgoing;

#[Tries(3)]
class AcknowledgeReceipt implements ShouldQueue
{
    use Queueable;

    public function __construct(public int $inboundEmailId)
    {
    }

    public function handle(Mailbox $mailbox): void
    {
        $email = InboundEmail::with('team')->findOrFail($this->inboundEmailId);

        if ($email->acknowledged_at !== null || preg_match('/^(mailer-daemon|postmaster|no-?reply)@/i', $email->from_address)) {
            return; // already answered, or a sender that should never get a reply
        }

        $original = $mailbox->get($email->mailcycle_message_id);
        $count = count($email->files);

        try {
            $mailbox->send(new Outgoing(
                from: $email->team->inbox_email,
                to: $original->replyTo,
                subject: str_starts_with($original->subject, 'Re:') ? $original->subject : "Re: {$original->subject}",
                text: $count > 0
                    ? "Thanks, we filed {$count} ".str('file')->plural($count)." under {$email->team->name}.\n"
                    : "Thanks, we filed this email under {$email->team->name}. Attach a PDF or photo next time and we will keep the file too.\n",
                replyTo: $original,
            ));
        } catch (ApiException $e) {
            if ($e->status() === 429) {
                $this->release(120);

                return;
            }
            throw $e;
        }

        $email->update(['acknowledged_at' => now()]);
    }
}

How it works:

  • replyTo: $original puts the answer in the same thread. The SDK sends the original message’s id and its Message-ID, so Gmail, Outlook and Apple Mail show the confirmation under the forwarded receipt.
  • $original->replyTo is where an answer should go: the sender’s Reply-To if they set one, otherwise their From address.
  • #[Tries(3)] is Laravel 13’s attribute for the retry count. If your Laravel version has no queue attributes yet, public $tries = 3; does the same.
  • A 429 releases the job for two minutes rather than failing it, because sending limits reset on their own. Any other API error is thrown, so Laravel’s normal retry and failed-job handling apply, and $e->apiCode() in your failed-job log says what happened.
  • The sender check stops an endless back and forth with bounce messages and no-reply senders, and acknowledged_at makes a retried job send at most once.

For the error codes you might see and what to do about each, the error handling section of the PHP send tutorial has a full list.

Step 6: Receive email in Laravel on a signed webhook route

Mailcycle sends a POST to your URL each time mail arrives. The body is JSON with an event id, a type, a timestamp and a payload, and for message.received the payload carries messageId and inboxId (the address’s id). It carries ids, never mail content, so the route stays small.

Exclude the webhook from CSRF in bootstrap/app.php

Routes in routes/web.php check a CSRF token on every POST, and Mailcycle has no token to send, so the webhook needs an exception. Add it in bootstrap/app.php, together with an alias for the signature middleware:

<?php

use App\Http\Middleware\VerifyMailcycleSignature;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware): void {
        $middleware->preventRequestForgery(except: ['webhooks/mailcycle']);

        $middleware->alias([
            'mailcycle.signature' => VerifyMailcycleSignature::class,
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions): void {
        $exceptions->shouldRenderJsonWhen(
            fn (Request $request) => $request->is('api/*') || $request->expectsJson(),
        );
    })->create();

On Laravel 11 and 12 the method is validateCsrfTokens(except: [...]). Laravel 13 renamed it to preventRequestForgery and keeps the old name as a deprecated alias.

Exclude the one path, not a wildcard such as webhooks/*, so a route you add later does not lose its protection by accident. The signature check below takes the place of the token for this route. Putting the route in routes/api.php instead also works, since API routes have no CSRF check, but then the route lives away from the rest of the app’s routes and middleware, which is why this app keeps it in web.php.

Verify the Mailcycle signature in route middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mailcycle\WebhookSignature;
use Symfony\Component\HttpFoundation\Response;

class VerifyMailcycleSignature
{
    public function handle(Request $request, Closure $next): Response
    {
        $secret = (string) config('services.mailcycle.webhook_secret');

        $valid = $secret !== '' && WebhookSignature::verifyNow(
            $secret,
            $request->getContent(),
            $request->header('Mailcycle-Signature'),
        );

        abort_unless($valid, 401, 'Invalid signature');

        return $next($request);
    }
}

$request->getContent() is the body exactly as it arrived, which is what the signature covers. The header holds a Unix timestamp and an HMAC-SHA256 of the timestamp and the body, keyed with your webhook secret. verifyNow() compares it in constant time and refuses deliveries more than five minutes old, so a captured request cannot be replayed later. An empty secret refuses everything, which is the safe failure when .env is missing the value.

As route middleware, the check runs before the controller, and any other webhook routes you add can reuse it with ->middleware('mailcycle.signature').

The webhook controller

By the time the controller runs, the body is known to be genuine, so it can read the JSON and hand the work to the queue:

<?php

namespace App\Http\Controllers;

use App\Jobs\ProcessInboundEmail;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

class MailcycleWebhookController extends Controller
{
    public function __invoke(Request $request): Response
    {
        if ($request->input('type') === 'message.received') {
            ProcessInboundEmail::dispatch(
                (string) $request->input('payload.messageId'),
                (string) $request->input('payload.inboxId'),
            );
        }

        return response()->noContent();
    }
}

Mailcycle waits up to ten seconds for a 2xx, and retries a failed delivery several times over about a day and a half. Dispatching a job and returning 204 straight away keeps the route well inside that window. Every other event type, including the webhook.test event the app sends when you press Send test, gets a 204 and is ignored.

Add the webhook in the Mailcycle app

In the app, open API, then the Webhooks tab, add your URL ending in /webhooks/mailcycle, and subscribe it to message.received. Copy the secret into MAILCYCLE_WEBHOOK_SECRET, then run php artisan config:clear (or config:cache in production).

Mailcycle calls webhooks from the internet, so a http://localhost URL is refused. While you build, run an HTTPS tunnel such as Cloudflare Tunnel or ngrok in front of php artisan serve and add the tunnel’s URL. The webhooks guide has the commands. If you prefer to add it from PHP, the SDK can do it from a signed-in session: $mc->webhooks()->create($url, ['message.received'], 'Receipts') returns the secret once.

Step 7: Store incoming email and attachments in Laravel

The job does the real work: it fetches the message, saves the receipt files, records the email and queues the confirmation.

<?php

namespace App\Jobs;

use App\Models\InboundEmail;
use App\Models\Team;
use App\Services\Mailbox;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Storage;
use RuntimeException;

#[Tries(5)]
#[Backoff([10, 60, 300])]
class ProcessInboundEmail implements ShouldQueue
{
    use Queueable;

    /** The file types this app files as receipts. */
    private const KEEP = ['application/pdf', 'image/jpeg', 'image/png', 'image/heic'];

    public function __construct(public string $messageId, public string $addressId)
    {
    }

    public function handle(Mailbox $mailbox): void
    {
        if (InboundEmail::where('mailcycle_message_id', $this->messageId)->exists()) {
            return; // a webhook retry for mail we already filed
        }

        $team = Team::where('inbox_address_id', $this->addressId)->first();
        if ($team === null) {
            return; // an address this app did not create
        }

        $message = $mailbox->get($this->messageId);
        if (! $message->opened) {
            $this->fail(new RuntimeException('Message did not open. Is MAILCYCLE_PHRASE set on this worker?'));

            return;
        }

        $files = [];
        foreach ($message->attachments as $attachment) {
            if (! $attachment->stored || ! in_array($attachment->mimeType, self::KEEP, true)) {
                continue;
            }
            $name = basename(str_replace('\\', '/', $attachment->filename));
            $path = "receipts/{$team->id}/{$message->id}/{$name}";
            Storage::put($path, $mailbox->attachment($message, $attachment->index));
            $files[] = $path;
        }

        $email = InboundEmail::createOrFirst(
            ['mailcycle_message_id' => $message->id],
            [
                'team_id' => $team->id,
                'from_address' => $message->fromAddress,
                'subject' => $message->subject,
                'body' => $message->text,
                'files' => $files,
                'received_at' => Carbon::parse($message->receivedAt),
            ],
        );

        if ($email->wasRecentlyCreated) {
            AcknowledgeReceipt::dispatch($email->id);
        }
    }
}

What each part is for:

  • The exists() check returns early on a webhook retry without fetching the message again.
  • The team lookup uses the address id from the event, which is why the controller saved inbox_address_id. An email to an address this app did not make is ignored.
  • $message->opened is false when the worker has no phrase or the wrong one. The job fails with a message that says so, rather than storing an empty row.
  • Attachments are fetched one at a time with $mailbox->attachment() and written with Storage::put() to the default disk, which is storage/app/private on a new Laravel app and can be S3 in production. The file name comes from whoever sent the email, so the job takes basename() of it and keeps only PDFs and images.
  • createOrFirst() inserts the row, and if two copies of the job race, the unique index makes the second one find the first row instead of failing. Only the job that created the row queues AcknowledgeReceipt, so the team gets one confirmation per email.
  • #[Backoff([10, 60, 300])] spaces out retries when the API cannot be reached: ten seconds, then a minute, then five minutes for the attempts after.

Mailcycle keeps mail for 7 days by default, and up to 90 if you set retentionDays on the address. The row and the stored files are your app’s own copy, so mail doesn’t pile up on the Mailcycle side and your records stay as long as you need them.

Act on the email as well as storing it

Storing is the start. The same job is the place to read an amount from the PDF, match the email to an expense by its subject, or notify the team. Laravel events fit here: fire an InboundEmailReceived event after createOrFirst() and let listeners do each task, so the job stays short.

Step 8: Feature tests for the webhook route and the job

Two test classes cover the parts that are easy to get wrong: the signature check and the storage logic.

Test the signed webhook route

WebhookSignature::header() builds the same header Mailcycle sends, so the test can sign a delivery the way the real service does:

<?php

namespace Tests\Feature;

use App\Jobs\ProcessInboundEmail;
use Illuminate\Support\Facades\Queue;
use Illuminate\Testing\TestResponse;
use Mailcycle\WebhookSignature;
use Tests\TestCase;

class MailcycleWebhookTest extends TestCase
{
    private const SECRET = 'test-webhook-secret';

    protected function setUp(): void
    {
        parent::setUp();

        config(['services.mailcycle.webhook_secret' => self::SECRET]);
        Queue::fake();
    }

    private function deliver(array $event, ?string $signature = null): TestResponse
    {
        $body = json_encode($event);

        return $this->call('POST', '/webhooks/mailcycle', server: [
            'CONTENT_TYPE' => 'application/json',
            'HTTP_MAILCYCLE_SIGNATURE' => $signature ?? WebhookSignature::header(self::SECRET, $body, time()),
        ], content: $body);
    }

    private function received(): array
    {
        return [
            'id' => 'evt_1',
            'type' => 'message.received',
            'createdAt' => now()->toIso8601String(),
            'payload' => ['messageId' => 'msg_1', 'inboxId' => 'ibx_1'],
        ];
    }

    public function test_a_signed_delivery_queues_the_email(): void
    {
        $this->deliver($this->received())->assertNoContent();

        Queue::assertPushed(ProcessInboundEmail::class, fn ($job) => $job->messageId === 'msg_1' && $job->addressId === 'ibx_1');
    }

    public function test_a_forged_signature_is_refused(): void
    {
        $forged = WebhookSignature::header('someone-elses-secret', json_encode($this->received()), time());

        $this->deliver($this->received(), $forged)->assertUnauthorized();

        Queue::assertNothingPushed();
    }

    public function test_an_old_delivery_is_refused(): void
    {
        $old = WebhookSignature::header(self::SECRET, json_encode($this->received()), time() - 600);

        $this->deliver($this->received(), $old)->assertUnauthorized();
    }

    public function test_other_events_are_accepted_and_ignored(): void
    {
        $this->deliver(['id' => 'evt_2', 'type' => 'inbox.created', 'payload' => ['inboxId' => 'ibx_1']])->assertNoContent();

        Queue::assertNothingPushed();
    }
}

$this->call() with content: posts the body byte for byte, which matters because the signature covers those exact bytes. Queue::fake() stops the job from running, so the test checks only the route.

Test the job with a mocked Mailbox

The job test builds a real Mailcycle\Models\Message with an attachment whose name tries to climb out of the folder, mocks Mailbox, and runs the job twice to stand in for a retried delivery:

<?php

namespace Tests\Feature;

use App\Jobs\AcknowledgeReceipt;
use App\Jobs\ProcessInboundEmail;
use App\Models\Team;
use App\Services\Mailbox;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;
use Illuminate\Support\Facades\Storage;
use Mailcycle\Models\Attachment;
use Mailcycle\Models\Message;
use Mockery\MockInterface;
use Tests\TestCase;

class ProcessInboundEmailTest extends TestCase
{
    use RefreshDatabase;

    private function message(): Message
    {
        return new Message(
            id: 'msg_1', addressId: 'ibx_1', receivedAt: '2026-11-29T10:00:00Z',
            read: false, starred: false, folder: 'inbox', sizeBytes: 2048, sentVia: null,
            keyEpoch: 0, opened: true, fromAddress: 'sam@example.com', fromName: 'Sam',
            replyTo: 'sam@example.com', to: 'acme-k2x9@example.net', subject: 'Taxi receipt',
            text: 'Receipt attached.', html: '', safeHtml: '', blocked: [],
            messageId: '<abc@example.com>',
            attachments: [new Attachment(0, '../../taxi.pdf', 'application/pdf', 1024, null, true)],
        );
    }

    public function test_it_files_the_email_and_its_receipt_once(): void
    {
        Storage::fake();
        Queue::fake([AcknowledgeReceipt::class]);
        $team = Team::create(['name' => 'Acme', 'owner_email' => 'owner@example.com', 'inbox_address_id' => 'ibx_1', 'inbox_email' => 'acme-k2x9@example.net']);

        $this->mock(Mailbox::class, function (MockInterface $mock) {
            $mock->shouldReceive('get')->once()->with('msg_1')->andReturn($this->message());
            $mock->shouldReceive('attachment')->once()->andReturn('%PDF-1.7 fake');
        });

        ProcessInboundEmail::dispatch('msg_1', 'ibx_1');
        ProcessInboundEmail::dispatch('msg_1', 'ibx_1'); // the same delivery again

        $this->assertDatabaseCount('inbound_emails', 1);
        $email = $team->inboundEmails()->sole();
        $this->assertSame(["receipts/{$team->id}/msg_1/taxi.pdf"], $email->files);
        Storage::assertExists("receipts/{$team->id}/msg_1/taxi.pdf");
        Queue::assertPushed(AcknowledgeReceipt::class, 1);
    }
}

Queue::fake([AcknowledgeReceipt::class]) fakes only the confirmation job, so ProcessInboundEmail still runs on the sync queue that phpunit.xml sets, while the send is only recorded. Storage::fake() swaps the disk for a temporary one. The mock expects get once, so the test also proves the second run stopped at the exists() check.

Run them with php artisan test. On our run, all seven tests passed, the two from the Laravel starter included.

Check the CSRF exclusion with a real request

Laravel switches off CSRF checks while tests run, so a passing test suite says nothing about the exclusion in bootstrap/app.php. Check it against a running app instead:

php artisan serve --port=8765
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8765/webhooks/mailcycle
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://127.0.0.1:8765/teams/1/inbox

The webhook should answer 401: it got past CSRF and was refused by the signature middleware. The dashboard route should answer 419, the CSRF refusal. When we removed the exclusion line, the webhook answered 419 too, which is the failure this check is there to catch.

Run the PHP email API flow end to end

We ran the whole app on Laravel 13.44 and PHP 8.5 against a live Mailcycle account on Scale, with a second address on the same account playing the team owner:

  1. POST /teams/1/inbox created acme-studio-gftb@ and sent “Your receipts address for Acme Studio”. The action took about three seconds, creating the address and sending included.
  2. The owner replied to that email with taxi-receipt.pdf attached, and it arrived at the team address.
  3. A signed message.received delivery for it returned 204, and the job stored one row and the PDF under receipts/1/.
  4. The same delivery again returned 204 and changed nothing.
  5. AcknowledgeReceipt sent “Re: Your receipts address for Acme Studio” with the text “Thanks, we filed 1 file under Acme Studio.”, and it landed in the owner’s thread.

The delivery in step 3 was signed with WebhookSignature::header() and posted to the app, which is the same request Mailcycle makes once the webhook points at a public URL.

Taking the Laravel integration to production

  • Run a queue worker. Both jobs need one: php artisan queue:work, kept alive by Supervisor or your platform’s process manager, or Laravel Horizon on Redis.
  • Keep the phrase where it is needed. In this app the web servers create addresses and the workers open mail, so both need it. Store it as a secret in your platform, never in the repository.
  • Use one API key per environment, so you can revoke staging’s without touching production’s.
  • Bring your own domain on Scale with the domains guide, and pass domain: to NewAddress so teams get addresses on it.
  • Watch the limits. The rate limits reference lists sends a day and per hour for each plan, and the 429 release in step 5 already handles a busy hour.
  • Give the inbox to an AI agent as well. The same team addresses can be opened by the Mailcycle MCP server, so Claude, Cursor or any other MCP client can read receipts and draft answers for a person to check.

Next steps

FAQ

What is the best way to use a PHP email API in Laravel?

Put the client in the service container and inject it. A dedicated MailcycleServiceProvider binds one Mailcycle client as a singleton, built from config('services.mailcycle'), and a small Mailbox class wraps the calls your app makes. Controllers and jobs type-hint Mailbox, so feature tests can swap it with $this->mock(). The settings live in .env and are read only in config/services.php, which keeps php artisan config:cache working.

How do I integrate an email API into a Laravel app?

Install the PHP SDK with Composer, add a mailcycle block to config/services.php, bind the client in a service provider, then send with messages()->send(new Outgoing(...)) from a controller or a queued job. For mail coming in, add a message.received webhook that points at a route in routes/web.php, exclude that route from CSRF in bootstrap/app.php, and check the signature in route middleware. This tutorial builds each step in that order.

How do I receive email in PHP with Laravel?

Mailcycle posts a signed message.received event to your route with the message id and the address id. Your middleware checks the Mailcycle-Signature header against the raw body with WebhookSignature::verifyNow(), the controller queues a job, and the job fetches the message with messages()->get($id). It arrives parsed and opened in your PHP process, with sender, subject, text, HTML and attachments.

How do I exclude a webhook route from CSRF protection in Laravel?

In Laravel 13, call $middleware->preventRequestForgery(except: ['webhooks/mailcycle']) inside withMiddleware() in bootstrap/app.php. In Laravel 11 and 12 the same call is $middleware->validateCsrfTokens(except: [...]). Exclude only the webhook path, and protect it with the signature check instead. A POST to the route without a token should then reach your middleware (401 when unsigned) and not stop at 419.

Should a Laravel app send email from a controller or from a queued job?

Send from the controller when the user is waiting for the result and the send is part of the action, such as emailing a new address to its owner. Send from a queued job when the email follows from something in the background, such as confirming a receipt that arrived by webhook. A job gets its own retries through #[Tries] and #[Backoff], and can release() itself when the API answers 429.

How do I test a Laravel webhook endpoint that checks a signature?

Build the signature in the test with WebhookSignature::header($secret, $body, time()), post the exact body with $this->call('POST', ...), and use Queue::fake() to assert the job was pushed. Add a forged signature and a ten-minute-old one, and assert both get 401. Laravel switches off CSRF checks while tests run, so prove the CSRF exclusion separately with a real request against php artisan serve.

Where should a Laravel app store incoming email and attachments?

Store the parts you need in your own table, keyed by the Mailcycle message id with a unique index, and write attachments with the Storage facade under a path you build yourself. Take basename() of the sender's file name and keep only the types you expect. Mailcycle keeps mail for 7 days by default and up to 90, so anything you want for longer belongs in your database and storage.

How do I stop duplicate webhook deliveries creating duplicate rows in Laravel?

Give the message id column a unique index and create the row with InboundEmail::createOrFirst(). A retry finds the existing row, wasRecentlyCreated is false, and the job skips the follow-up work. A cheap exists() check at the top of the job also saves fetching the message again.

Which Mailcycle plan does a Laravel app need for a PHP email API?

API keys and webhooks start on Operator, which also gives 250 addresses. Sending from an API key comes with Scale ($19/month), along with 1,000 addresses, 250 sends a day and up to 10 of your own domains. See pricing and Plans and limits.