How to Receive Email in PHP with an Email API: Read the Inbox, Save Attachments and Handle Webhooks

A PHP email API to receive and read mail without the IMAP extension: create an address, wait for a message, save attachments, and handle a Laravel webhook.

By · · 12 min read

PHP code that reads the newest message in a Mailcycle inbox with the PHP SDK

You want to receive email in PHP: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your Laravel app. The classic route is the IMAP extension: imap_open() a mailbox, search it and parse the structure of each message. Since PHP 8.4 that extension is no longer bundled and has to be installed from PECL, and it needs a mailbox and its password. If what you want is “give my code an address and let it read what arrives”, a PHP email API is shorter.

This tutorial shows how to receive and read email in PHP with Mailcycle’s PHP SDK, the mailcycle/mailcycle Composer package. You’ll create an address, list and open messages, save attachments to disk, wait for the next email, and then get new mail pushed to a Laravel route by webhook.

It is the receiving half of How to send email from PHP, which covers sending, HTML, attachments you send and threaded replies. This one goes deep on the inbox.

Quick answer: how to receive email in PHP

Install the package, sign in with your recovery phrase, create an address, and call waitFor(). It returns when a message arrives, parsed and decrypted, with the sender, subject, text, HTML and attachments as plain properties.

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

require __DIR__ . '/vendor/autoload.php';

use Mailcycle\Mailcycle;
use Mailcycle\NewAddress;
use Mailcycle\WaitFor;

$mc = Mailcycle::signIn(getenv('MAILCYCLE_PHRASE'));

$address = $mc->addresses()->create(new NewAddress(prefix: 'inbound', label: 'PHP inbox'));
echo 'Send an email to ', $address->emailAddress, "\n";

$message = $mc->messages()->waitFor(new WaitFor(addressId: $address->id, timeout: 300));
echo $message->fromAddress, ': ', $message->subject, "\n";
echo $message->text, "\n";

Run it, send an email to the address it prints from any mail app, and the script prints what you sent. The rest of this guide is what a real app needs around that: paging, attachments, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the PHP SDK lists, waits for or receives it by webhook, and your PHP code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your PHP code reads it with the PHP SDK, by waiting for it or from a webhook.

Prerequisites

  • PHP 8.1 or later with the sodium, openssl, curl, json and mbstring extensions, which most builds include. Check with php -v and php -m.
  • Composer.
  • A Mailcycle account. Receiving works on every plan when your code signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
  • Your recovery phrase, in an environment variable named MAILCYCLE_PHRASE, for any process that opens mail.
  • Laravel, only for the webhook section. Symfony and Slim work the same way.

Step 1: Install the PHP package

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

The first line adds Mailcycle’s own Composer repository to your project. After that, composer require, composer update and the lock file work as they do for any other package. Version 0.3.0 is current at the time of writing, with no dependencies beyond the PHP extensions above.

Step 2: Sign in and create an address

Mailcycle::signIn($phrase) works on every plan. With an Operator plan or above you can also use an API key:

use Mailcycle\Mailcycle;

$phrase = getenv('MAILCYCLE_PHRASE');
$apiKey = getenv('MAILCYCLE_API_KEY');

$mc = $apiKey
    ? Mailcycle::withApiKey($apiKey, $phrase)
    : Mailcycle::signIn($phrase);

An address that receives mail needs a public key the mail server can encrypt to. addresses()->create() derives that key from your phrase and uploads only the public half, so it needs a client built with the phrase.

use Mailcycle\NewAddress;

$address = $mc->addresses()->create(new NewAddress(
    prefix: 'invoices',
    label: 'Supplier invoices',
    retentionDays: 30,
));
echo $address->emailAddress, ' ', $address->id, "\n";

foreach ($mc->addresses()->list() as $existing) {
    echo $existing->emailAddress, ' ', $existing->label, ' ', $existing->receives ? 'receives' : 'no key yet', "\n";
}

The options on NewAddress:

  • prefix: 'invoices' gives invoices- plus a random ending on a shared domain.
  • style (a NameStyle) rolls a name in that style, and $mc->addresses()->rollNames($style) lists some to choose from.
  • localPart asks for an exact name. Any name you type needs Scale or above, and so does domain with your own domain.
  • label is encrypted on your machine, so the server stores it as ciphertext.
  • retentionDays is 1 to 90, and 7 by default.

Save $address->id, the ibx_... id: every reading call takes it.

Step 3: List and read emails in the inbox

messages()->list() returns one page of a folder, newest first:

$page = $mc->messages()->list($address->id, limit: 20);

foreach ($page->messages as $message) {
    $flag = $message->read ? ' ' : '*';
    echo $flag, ' ', $message->receivedAt, ' ', $message->fromAddress, ' ', $message->subject, "\n";
}

if ($page->nextCursor !== null) {
    $older = $mc->messages()->list($address->id, limit: 20, cursor: $page->nextCursor);
    echo count($older->messages), " older messages on the next page\n";
}

limit goes up to 200. nextCursor is opaque: pass it back as cursor as it came, and it is null on the last page. To walk a whole folder, all() pages for you:

$invoices = array_filter(
    $mc->messages()->all($address->id),
    fn ($message) => str_contains(strtolower($message->subject), 'invoice') && count($message->attachments) > 0,
);
echo count($invoices), " invoices with files attached\n";

Message content is encrypted, so you decrypt and then filter in PHP, as above. Pass folder: 'sent', 'junk', 'trash' or 'starred' to read another folder.

What is in a Message

Each Message is a read-only object, already parsed from MIME and decrypted:

Property What it holds
id, addressId The message’s msg_... id and the address it arrived at.
receivedAt When it arrived, as an ISO 8601 string in UTC.
fromAddress, fromName The sender’s address and display name.
replyTo Where a reply should go: the Reply-To header if set, otherwise From.
to, subject The recipient and the subject line.
text The plain-text body.
html The HTML body exactly as sent. Do not render this one.
safeHtml The HTML with remote images, trackers and embeds removed.
attachments An array of Attachment: index, filename, mimeType, size, contentId, stored.
messageId The sender’s Message-ID header, used to thread a reply.
read, starred, folder The message’s state.
opened false if it could not be decrypted: no phrase, or the wrong one.

A message that does not open comes back with opened set to false and empty content rather than throwing, so one bad message never hides the rest of a page.

Read the email body in PHP: text, html and safeHtml

Most mail carries a plain-text and an HTML part. Use text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use safeHtml:

$message = $mc->messages()->get('msg_91be02c4a7d1');

if (!$message->opened) {
    exit("This message did not open: check the recovery phrase.\n");
}

echo $message->text !== '' ? $message->text : "(no plain-text part)\n";

if ($message->safeHtml !== '') {
    file_put_contents('preview.html', $message->safeHtml);
    echo count($message->blocked), " remote items taken out\n";
}

get() fetches one message by id, from any folder. safeHtml is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. If you embed it in a page of your own, put it in a sandboxed <iframe>.

Download email attachments in PHP

Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and attachment() opens them on your machine. This function saves a message’s files safely:

use Mailcycle\Mailcycle;
use Mailcycle\Models\Message;

/** @return list<string> the paths written */
function saveAttachments(Mailcycle $mc, Message $message, string $folder): array
{
    $target = $folder . '/' . $message->id;
    $saved = [];
    foreach ($message->attachments as $attachment) {
        if (!$attachment->stored) {
            continue; // an empty part: nothing to fetch
        }
        if ($attachment->contentId !== null) {
            continue; // an image the HTML shows inline, like a logo
        }

        $bytes = $mc->messages()->attachment($message, $attachment->index); // opened on this machine
        if (!is_dir($target)) {
            mkdir($target, 0700, true);
        }
        $name = basename(str_replace('\\', '/', $attachment->filename));
        $name = preg_replace('/[^\w.\- ]/', '_', $name) ?: 'attachment';
        $path = $target . '/' . $attachment->index . '-' . $name;
        file_put_contents($path, $bytes);
        $saved[] = $path;
    }
    return $saved;
}

Then process every unread message that has files, and mark each one read so the next run skips it:

foreach ($mc->messages()->all($address->id) as $message) {
    if ($message->read || count($message->attachments) === 0) {
        continue;
    }
    foreach (saveAttachments($mc, $message, 'downloads') as $path) {
        echo "saved $path\n";
    }
    $mc->messages()->markRead($message->id);
}

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../.env is a classic path-traversal trick. basename() keeps the last path component, the character filter keeps the rest tame, and the index prefix keeps two files called invoice.pdf apart.
  • stored is false for a part that had no body. Skip it.
  • contentId marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • mimeType and size let you keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That is the job a PHP email parser does for attachments, without walking a MIME structure or decoding base64.

Wait for the next email in PHP

waitFor() returns when a matching message arrives, opened. It is the shortest way to read a verification email in a feature test, or to wait for a reply:

use Mailcycle\Exception\ApiException;
use Mailcycle\WaitFor;

$started = new DateTimeImmutable(); // take the time before the email is triggered

// ...trigger the email here: submit a sign-up form, call your own API...

try {
    $message = $mc->messages()->waitFor(new WaitFor(
        addressId: $address->id,
        subject: 'verify',
        since: $started,
        timeout: 120,
    ));
} catch (ApiException $error) {
    if ($error->apiCode() === 'timeout') {
        exit("No verification email within two minutes.\n");
    }
    throw $error;
}

if (preg_match('/\b(\d{6})\b/', $message->text, $match)) {
    echo 'code: ', $match[1], "\n";
} else {
    echo 'No code in: ', substr($message->text, 0, 200), "\n";
}

How it behaves:

  • since is the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to when waitFor is called.
  • from and subject match text the sender or subject contains, ignoring case. addressId limits the wait to one address.
  • timeout is in seconds, 60 by default. When it runs out you get an ApiException with apiCode() of timeout.
  • pollEvery (five seconds by default) is how often it checks when the live stream is not available.

In PHPUnit, create the address in setUp() and delete it in tearDown() with $mc->addresses()->delete($address->id). Pest and Laravel Dusk use the same calls.

Mark as read, star, move and delete

These calls change state only, so they do not open any content:

Call What it does
$mc->messages()->markRead($id) Marks read. markRead($id, false) marks unread.
$mc->messages()->star($id) Stars it. star($id, false) unstars.
$mc->messages()->moveTo($id, 'junk') Moves to 'inbox', 'junk' or 'trash'.
$mc->messages()->delete($id) Deletes it now.
$mc->messages()->emptyTrash() Deletes everything in the trash and returns how many.

Get new email pushed to Laravel with a webhook

Mailcycle can tell your app the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Add a webhook in the app under API, on the Webhooks tab, or from PHP with a signed-in session:

$created = $mc->webhooks()->create(
    'https://example.com/api/hooks/mailcycle',
    ['message.received'],
    'Inbound mail',
);
echo $created->secret, "\n"; // whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET

The URL must be HTTPS. For local development, expose your dev server through a tunnel. Then the receiving route, in routes/api.php so CSRF protection does not reject it:

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;
use Mailcycle\Mailcycle;
use Mailcycle\WebhookSignature;

Route::post('/hooks/mailcycle', function (Request $request) {
    $raw = $request->getContent(); // the exact body, before any parsing
    $secret = config('services.mailcycle.webhook_secret');

    if (!WebhookSignature::verifyNow($secret, $raw, $request->header('Mailcycle-Signature'))) {
        abort(401);
    }

    $eventId = $request->header('Mailcycle-Event-Id');
    if ($eventId && !Cache::add("mailcycle:event:$eventId", true, now()->addDays(2))) {
        return response()->noContent(); // a retry of an event already handled
    }

    $event = json_decode($raw, true);
    if (($event['type'] ?? null) === 'message.received') {
        ProcessInboundMail::dispatch($event['payload']['messageId']); // answer fast, work in a queue job
    }
    return response()->noContent();
});

And the queued job that does the reading:

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mailcycle\Mailcycle;

class ProcessInboundMail implements ShouldQueue
{
    use Dispatchable;

    public function __construct(private string $messageId)
    {
    }

    public function handle(): void
    {
        $mc = Mailcycle::signIn(config('services.mailcycle.phrase'));
        $message = $mc->messages()->get($this->messageId); // fetched by id, opened here
        if (!$message->opened) {
            return;
        }

        $saved = saveAttachments($mc, $message, storage_path('app/inbound'));
        logger()->info("{$message->fromAddress}: {$message->subject} (" . count($saved) . ' files)');
        $mc->messages()->markRead($message->id);
    }
}

saveAttachments is the function from the attachments section. What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. verifyNow checks it in constant time and refuses a timestamp more than five minutes old. Check the body as it arrived: a body that was decoded and re-encoded will not match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. The route dispatches a job and returns, and the job does the fetching and saving.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. Cache::add only succeeds the first time, across every worker that shares the cache.
  • Symfony and Slim follow the same steps: read the raw body, verify, fetch by id.

You can test the route without a live webhook. WebhookSignature::header($secret, $body, time()) builds the header Mailcycle would send. Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

The IMAP extension and an email API in PHP

imap_open() connects to a mailbox: you give it a host, port 993 and credentials, then call imap_search(), imap_fetchstructure() and imap_fetchbody() and decode each part yourself. Libraries such as php-imap wrap that in objects. It is the right tool when the mail already lives in a mailbox you own, like a shared support inbox, and your code needs to read it where it is.

An email API fits when your code needs addresses of its own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.

IMAP extension Mailcycle PHP SDK
Install PECL extension from PHP 8.4 composer require mailcycle/mailcycle
You need An IMAP mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider $mc->addresses()->create() in code
Parsing imap_fetchstructure() and manual decoding Parsed properties: text, html, attachments
Tracker-free HTML Strip it yourself safeHtml, with blocked listing what was removed
Attachments Decode each part $mc->messages()->attachment($message, $index)
New-mail push Poll the mailbox Webhooks and the event stream
Wait for one email Write the loop yourself waitFor()
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

Do the waiting in a queued job, not a web request

PHP-FPM gives each request a worker for as long as it runs, so a web request that waits a minute for an email ties one up. Put the wait in a queue worker instead. In Laravel, a job takes the address id, waits and stores the result.

final class ReadVerificationEmail implements ShouldQueue
{
    use Dispatchable, Queueable;

    public int $timeout = 90;

    public function __construct(private string $addressId, private string $userId, private string $since) {}

    public function handle(Mailcycle $mc): void
    {
        $message = $mc->messages()->waitFor(new WaitFor(
            addressId: $this->addressId,
            subject: 'verify',
            since: new DateTimeImmutable($this->since),
            timeout: 60,
        ));
        preg_match('/\b\d{6}\b/', $message->text, $m);
        User::whereKey($this->userId)->update(['email_code' => $m[0] ?? null]);
    }
}

Dispatch it with the time taken before the sign-up request, as in ReadVerificationEmail::dispatch($address->id, $user->id, (new DateTimeImmutable())->format(DATE_ATOM)), so the wait counts mail from that moment on. Set the job’s $timeout above the wait timeout, so the queue does not kill the job before the wait finishes. Bind the client in a service provider with $this->app->singleton(Mailcycle::class, fn () => Mailcycle::signIn(config('services.mailcycle.phrase'))).

A scheduled command that files invoices

Laravel’s scheduler or a plain cron entry can run a console command every few minutes. The command lists the unread messages, saves each attachment and marks the message read, which is the pattern from the attachments section.

protected function schedule(Schedule $schedule): void
{
    $schedule->command('mail:file-invoices')->everyFiveMinutes()->withoutOverlapping();
}

withoutOverlapping() stops a slow run from stacking up behind the next one. For instant delivery, use the webhook controller instead and keep the command as a safety net.

A Pest test with a real address

Pest reads cleanly for this, with beforeEach and afterEach around the address:

beforeEach(fn () => $this->address = $this->mc->addresses()->create(new NewAddress(prefix: 'pest', retentionDays: 1)));
afterEach(fn () => $this->mc->addresses()->delete($this->address->id));

it('sends a sign-up code', function () {
    $since = new DateTimeImmutable();
    $this->post('/register', ['email' => $this->address->emailAddress])->assertCreated();

    $message = $this->mc->messages()->waitFor(new WaitFor(addressId: $this->address->id, since: $since, timeout: 60));
    expect($message->text)->toMatch('/\b\d{6}\b/');
});

Shared hosting and Composer

The package needs PHP 8.1 or later with the sodium, openssl, curl, json and mbstring extensions, which most builds include. On shared hosting without a queue, keep requests short: create the address in one request and read the message in a cron script, rather than waiting inside the page.

Receiving mail in Symfony or plain PHP

Nothing in the SDK depends on Laravel. In Symfony, register the client as a service in services.yaml with a factory that calls Mailcycle::signIn(), and run the wait from a Messenger handler so it happens on a worker and never in a controller. In plain PHP, a CLI script run by cron or supervisor does the same job: sign in, list what is new, save files and exit. Cache the session token between runs and pick it up with Mailcycle::resume($token, $phrase), so a script that runs every minute does not sign in sixty times an hour.

A webhook endpoint in plain PHP reads the body once with file_get_contents('php://input'), checks the signature header against those exact bytes, and returns 204 before doing the slow work. Echoing a short response early keeps PHP-FPM workers free.

Troubleshooting

  • The webhook signature never matches. Read the raw body with file_get_contents('php://input') before any middleware parses it, because the signature covers the exact bytes.
  • A web request times out waiting. Move the wait into a queued job or a cron script, as above, and keep requests short.
  • Messages have opened set to false and empty fields. The client has no phrase, or a phrase from a different account. Build it with Mailcycle::signIn($phrase).
  • Nothing arrives at a new address. Check $address->receives in $mc->addresses()->list(), and check the sender used the exact address, since prefixed names have a random ending.
  • ApiException with apiCode() of rate_limited (429). You are reading too much too fast. Back off, read only what is new, or switch to webhooks.
  • A 404 fetching an attachment. The part has stored set to false. Skip it.
  • The webhook route returns 401 for real deliveries. You are verifying a re-encoded body, or the wrong secret. Use $request->getContent() and the whsec_ secret of this webhook.

Every error code is listed in Errors.

Reply from PHP, or hand the inbox to an agent

To answer a message in the same thread, pass it as replyTo: on an Outgoing and call $mc->messages()->send(). Sending email from PHP covers that, along with the plans that send.

If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.

Next steps

FAQ

How do I receive email in PHP?

Give your code an address that receives mail, then read it with a client. With Mailcycle, add its Composer repository and run composer require mailcycle/mailcycle, sign in with Mailcycle::signIn($phrase), create an address with $mc->addresses()->create(), and call $mc->messages()->waitFor(). The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

Is there a PHP email API for reading incoming mail?

Yes. The Mailcycle PHP SDK creates addresses in code and returns each incoming message as an object with subject, text, safeHtml and attachments. It reads mail over HTTPS, so there is no IMAP extension, port or mailbox password.

How do I read emails from an inbox in PHP?

Call $mc->messages()->list($addressId, limit: 20) for one page, newest first, or $mc->messages()->all($addressId) to walk the whole folder. Each Message has fromAddress, subject, text, safeHtml, attachments and read. Pass folder: 'junk', 'trash', 'sent' or 'starred' to read another folder.

How do I download email attachments in PHP?

Each Message lists its files in $message->attachments, with filename, mimeType, size and index. Call $mc->messages()->attachment($message, $attachment->index) to get the bytes, opened on your machine, and write them with file_put_contents(). Clean the file name first with basename(), because it comes from the sender.

How can a PHP script wait for a new email?

Call $mc->messages()->waitFor(new WaitFor(addressId: ..., subject: ..., since: ..., timeout: ...)). It returns the first matching message. If nothing matches in time it throws an ApiException whose apiCode() is timeout.

How do I get notified when an email arrives in a Laravel app?

Add a webhook for message.received, point it at a route in routes/api.php, and check each delivery with WebhookSignature::verifyNow() against the raw body. The event carries the message id, so fetch the message with $mc->messages()->get(). Webhooks are on the Operator plan and above.

Why is the package installed from mailcycle.email and not Packagist?

It is served from Mailcycle's own Composer repository at https://mailcycle.email/php. The first install line adds that repository to your project's composer.json; after that, composer require, composer update and the lock file work as they do for any other package.

Why does the PHP client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The PHP client derives the same keys on your machine with libsodium and opens each message in your process. A message that does not open comes back with opened set to false.

Receive email in code