Receive email in real time with PHP
Receive email in PHP with a signed JSON webhook: install the SDK, run a receiver, configure a MailKite address, and test delivery. Here, live means event-driven delivery after the email arrives, with normal SMTP and forwarding delays; it does not promise an exact latency.
1. Prepare a receiving address
In MailKite, add a domain or claim an available hosted subdomain. Complete the verification shown in the dashboard before receiving. For your own domain, publish the exact MX record MailKite returns. Choose an address such as inbound@your-receiving-domain.
For a detailed setup walkthrough, use the quickstart and domain verification docs. Your HTTP receiver needs a public HTTPS URL; a development tunnel can expose local port 3000 during testing.
The shared demo repository contains the exact receiver sources, local checks and inbox inspector used by this series.
2. Configure the webhook and run the PHP receiver
Create a webhook route matching your receiving address and point it to https://your-app.example/hooks/mailkite, replacing the example host with your public HTTPS host. Copy that route's signing secret into the receiver's environment. Avoid a catch-all route if you only want mail for one address.
PHP 8.1+, Composer, and the PDO SQLite extension. Set MAILKITE_WEBHOOK_SECRET to the signing secret for your configured MailKite webhook, supplied through your environment or secret manager. You do not need an API key for local signature verification.
composer require mailkite/mailkite Read php://input before decoding JSON. This receiver saves the signed payload in SQLite with a unique message id; a duplicate delivery leaves the original row intact. Put the database outside the public document root in production.
<?php
// Docs: docs/website/content/live-receiving-email-series.md
require __DIR__ . '/vendor/autoload.php';
$secret = getenv('MAILKITE_WEBHOOK_SECRET');
if (!$secret) { throw new RuntimeException('Set MAILKITE_WEBHOOK_SECRET'); }
if (parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) !== '/hooks/mailkite') {
http_response_code(404); exit;
}
if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); exit; }
$mk = new \MailKite\Client('unused-for-verify');
$raw = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_MAILKITE_SIGNATURE'] ?? '';
if (!$mk->verifyWebhook($signature, $raw, $secret)) {
http_response_code(401); exit;
}
try { $event = json_decode($raw, true, 512, JSON_THROW_ON_ERROR); }
catch (JsonException $e) { http_response_code(400); exit; }
if (!is_array($event)) { http_response_code(400); exit; }
if (($event['type'] ?? '') === 'email.received') {
if (!is_string($event['id'] ?? null) || $event['id'] === '') {
http_response_code(400); exit;
}
try {
$db = new PDO('sqlite:' . (getenv('INBOX_DB') ?: __DIR__ . '/inbox.sqlite'));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('PRAGMA busy_timeout = 5000');
$db->exec('CREATE TABLE IF NOT EXISTS inbox (id TEXT PRIMARY KEY, payload TEXT NOT NULL)');
$insert = $db->prepare('INSERT INTO inbox (id, payload) VALUES (?, ?) ON CONFLICT(id) DO NOTHING');
$insert->execute([$event['id'], $raw]);
} catch (PDOException $e) { http_response_code(503); exit; }
}
header('Content-Type: application/json');
echo $mk->replyOk(); // SQLite's autocommit write has finished before we acknowledge.
Download the exact receiver shown above. Save it beside its dependencies, then start it with the environment variable already set:
php -S 127.0.0.1:3000 receive.php This example stores each event once in a local SQLite inbox before returning success. Use persistent disk; an ephemeral deployment can delete that inbox on restart. A separate worker should process stored events and track completion. Storage deduplication alone does not make external side effects exactly-once.
3. Test the exact receiver and address
Download the local signed test and run it with Node.js and the same webhook secret. It creates synthetic HTTP requests only, including a duplicate id and a tampered body; it sends no email. The first two requests should return the SDK's JSON acknowledgement, and the tampered one should return 401.
node check.mjs http://127.0.0.1:3000/hooks/mailkite Then send a real message to the exact receiving address to test routing. The dashboard's domain-webhook test uses a catch-all route; it does not test an exact-address route. See signature verification and delivery and retries.
Download the local inbox inspector to read stored message bodies, including Gmail's confirmation message. This displays mailbox contents in your own terminal; keep it off the public web.
python3 inspect-inbox.py inbox.sqlite 4. Check a real message and its payload
Send a new message to the MailKite receiving address. Confirm delivery in MailKite and receipt at the endpoint. The JSON event has type: "email.received", a stable id, sender and recipient address objects, decoded bodies, attachment metadata and authentication results.
- Body: use
text, falling back totextFromHtmlwhen the plain-text part is null. - Attachments: process the signed download URLs after durable acceptance, before they expire.
- Authentication: the webhook signature authenticates MailKite's delivery. It does not prove the original sender is trustworthy. Forwarding can change email-authentication results.
- Retries: replay a delivery and confirm your production handler does not create a second job for the same message id.
Troubleshoot the delivery boundary
| Symptom | Check |
|---|---|
| No message in MailKite | Receiving-domain verification, MX records, the destination address, and the provider's forwarding settings. |
| Message stored, no webhook | The route's exact address match and enabled webhook destination. |
| 401 response | The signing secret, raw body, signature header and server clock. Do not disable freshness checks to hide the problem. |
| 503 response | Database availability, persistent storage and write permissions. Replay after correcting the storage failure. |
| Duplicate application work | Unique message ids, queue deduplication and downstream side-effect idempotency. |
Continue with the complete event reference, other receiving guides or the companion implementation article.