Bounced deliveries in an Exim main log are the lines whose flag is **, in the field straight after the message id. Match that position, not the two characters anywhere on the line, and stream the file rather than reading it into memory:
/^(?<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?: [+-]\d{4})?)
(?<id>[A-Za-z0-9]{6}-[A-Za-z0-9]{6,11}-[A-Za-z0-9]{2,4})
(?<flag>\*\*|==) (?<rest>.*)$/x
Matching ** anywhere on a line with strpos($line, '**') !== false, and reading the whole file with file_get_contents(), both fail on real logs; the sections below show what each produces.
Table of Contents
The flags, from Exim’s specification
<= message arrival ** delivery failed; address bounced
=> normal message delivery == delivery deferred; temporary problem
-> additional address *> delivery suppressed by -N
Only ** is permanent. == is a retry (“delivery deferred; temporary problem”), and suppressing those addresses means you stop mailing people whose server was briefly busy. Blacklisting everything that a bare ** match returns is a separate mistake, as the next sections show.
Two shapes of failure line exist, both taken from the spec:
1995-12-19 16:20:23 0tRiQz-0002Q5-00 ** jim@trek99.example <jim@trek99.example>: unknown mail domain
2002-07-11 07:14:17 17SXDU-000189-00 ** ace400@pb.example R=dnslookup T=remote_smtp: SMTP error
from remote mailer after pipelined RCPT TO:<ace400@pb.example>: host pbmail3.py.example
[192.168.63.111]: 553 5.3.0 <ace400@pb.example>...Addressee unknown
Note the message ids. Those are the old 16-character form. Since Exim 4.97 the id is 23 characters (1uMkQZ-000000004Bs-2h1P rather than 16ZCW1-0005MB-00) because the process-id portion was widened. As of 6 October 2026, exim.org lists 4.100 as the current version, with a specification at revision 4.100 of 20 August 2026, and downloads.exim.org also holds a later 4.100.1 tarball dated 14 September 2026. A parser with a fixed-width id pattern breaks on every modern installation, which is why the pattern above counts a range.
What a strpos and file_get_contents reader returns
The strpos and file_get_contents() version, saved as old.php, run against a 16-line fixture built from the spec’s own examples, on PHP 8.5.8:
$ php old.php mainlog.fixture
newsletter@example.net
jim@trek99.example
ace400@pb.example
bounce.target@aol.example
forwarded.box@mailhost.example
listmail@local.example
MAILER-DAEMON@bad.example
legacy16@oldformat.example
Four of those eight are wrong. newsletter@example.net is the sender of a message that was delivered successfully: its <= line matched only because the subject was T="Weekly update **NEW** pricing". Feed that list into a suppression table and you have blocked your own sending address. listmail@local.example is a local pipe transport that exited 75, not a recipient. MAILER-DAEMON@bad.example is Exim’s own bounce message failing to deliver. A fourth, forwarded.box@mailhost.example, is the address the mail was forwarded to. The address on your list is the one in angle brackets after it.
A streaming reader that matches only the flag field
One line in memory at a time, and a flag test that cannot match the middle of a subject line:
function bounces(string $path): Generator
{
$fh = fopen($path, 'rb');
$nullSender = []; // message ids Exim generated itself (bounce messages)
try {
while (($line = fgets($fh)) !== false) {
$line = rtrim($line, "\r\n");
if (preg_match('/^\S+ \S+(?: \S+)? (\S+) <= <> /', $line, $r) === 1) {
$nullSender[$r[1]] = true;
continue;
}
$row = parse_line($line); // the anchored regex above
if ($row === null) {
continue;
}
$row['own_bounce'] = isset($nullSender[$row['message_id']]);
yield $row;
}
} finally {
fclose($fh);
}
}
bounces() calls parse_line(), which applies the anchored regex above and then extracts the address and SMTP code. This is the function, with the two flag constants it uses:
const FLAG_FAILED = '**'; // delivery failed; address bounced (spec ch.53 s.10)
const FLAG_DEFERRED = '=='; // delivery deferred; temporary problem (spec ch.53 s.9)
/**
* One Exim main-log line, split at the flag.
* Message ids are 16 chars before Exim 4.97 and 23 chars from 4.97 on, so the
* id is matched as "non-space" rather than by length.
*/
function parse_line(string $line): ?array
{
$re = '/^(?<ts>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?: [+-]\d{4})?)'
. ' (?<id>[A-Za-z0-9]{6}-[A-Za-z0-9]{6,11}-[A-Za-z0-9]{2,4})'
. ' (?<flag>\*\*|==) (?<rest>.*)$/';
if (preg_match($re, $line, $m) !== 1) {
return null; // not a delivery-outcome line
}
$rest = $m['rest'];
// "<final address> [<original address>] [R=... T=...: <error>]"
if (preg_match('/^(?<final>\S+)(?: <(?<orig>[^>]*)>)?/', $rest, $a) !== 1) {
return null;
}
$final = rtrim($a['final'], ':');
$orig = $a['orig'] ?? '';
// Pipe, file and :blackhole: deliveries are not recipients.
if (!str_contains($final, '@')) {
return null;
}
// The address you originally sent to is the one worth suppressing; after an
// alias or forward the final address belongs to somebody else's mailbox.
$address = ($orig !== '' && str_contains($orig, '@')) ? $orig : $final;
// SMTP status from the remote server, when the failure happened at SMTP time.
$code = null;
if (preg_match('/(?:^|[\s:])([45]\d\d)[ -](?:\d\.\d{1,3}\.\d{1,3}\b|[A-Za-z<])/', $rest, $c) === 1) {
$code = (int) $c[1];
}
return [
'ts' => $m['ts'],
'message_id' => $m['id'],
'flag' => $m['flag'],
'address' => strtolower($address),
'final' => strtolower($final),
'code' => $code,
'permanent' => $m['flag'] === FLAG_FAILED,
'reason' => trim($rest),
];
}
The exim_bounces.php block in how-to-scrape-bounced-exim-mail-logs.sh runs this same function, and the script also asserts the four false positives, the deferral and alias handling and the 128M memory failure against a generated fixture, with no Exim server involved.
What the streaming reader returns for the same fixture
$ php exim_bounces.php mainlog.fixture suppression.sqlite
suppress jim@trek99.example --- 2026-08-09 04:13:44
suppress ace400@pb.example 553 2026-08-09 04:13:44
defer marvin@endrest.example 2026-08-09 04:14:02
suppress bounce.target@aol.example 550 2026-08-09 04:15:10
suppress original.subscriber@legacy.example 552 2026-08-09 04:16:20
defer queued.user@slow.example 2026-08-09 04:17:00
skip mailer-daemon@bad.example (failure of a bounce message I generated)
suppress legacy16@oldformat.example --- 2026-08-09 04:22:40
Four differences from the strpos output are worth naming. Deferrals are reported and not suppressed. The pipe transport is dropped, because a final address with no @ is not a mailbox. Failures of messages whose own sender was <> (Exim’s bounces) are skipped, tracked by message id from the earlier <= <> line. And where a delivery failed after an alias expansion, the address recorded is the original envelope recipient in angle brackets, not the forwarded target: it is your list that needs correcting, not somebody else’s mailbox.
Streaming versus slurping the file, measured
On a generated 96,160,000-byte log (640,000 lines), both approaches counting the same 360,000 matches:
slurp matched=360000 peak_memory=238796800 bytes (227.7 MB)
stream matched=360000 peak_memory=2097152 bytes (2.0 MB)
At the common memory_limit = 128M, the first one does not run at all:
$ php -d memory_limit=128M old.php big.log
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted
(tried to allocate 20480 bytes) in old.php on line 5
#0 old.php(5): explode('\n', '2026-08-09 04:1...')
Line 5 is the explode(), which allocates a second copy of the whole file as an array on top of the string file_get_contents() already built. fgets() holds one line. The streaming reader finishes at the same 128M limit.
Bind your parameters
Everything this parser extracts is text somebody else chose. The recipient came from your list, but the error string, the host name and the SMTP response were written by a remote mail server, and Exim copies them into the log verbatim. Never concatenate any of it into SQL:
$ins = $pdo->prepare('INSERT INTO suppressed (address, code, first_seen, reason)
VALUES (:a, :c, :t, :r)
ON CONFLICT(address) DO UPDATE SET code = :c, reason = :r');
$ins->execute([':a' => $b['address'], ':c' => $b['code'],
':t' => $b['ts'], ':r' => $b['reason']]);
The same applies to anything else you do with those strings: no shell_exec, and escape them before putting them in HTML. A script that only prints the addresses does none of this; the risk arrives with the database that storing them implies.
Where the log is
/var/log/exim_mainlog is the cPanel and Red Hat path. On Debian and Ubuntu it is /var/log/exim4/mainlog, so take it from the command line rather than hard-coding a constant, and remember rotation: yesterday’s bounces are in mainlog.1 or a .gz.
Tested on fixtures, not on a live Exim server
No Exim server was run, so every log line here comes either from Exim’s own specification or from fixtures written to match it. The parser is proven against those, not against traffic from a live MTA. The SQLite insert was executed; a MySQL or PostgreSQL equivalent was not. The claim that Exim 4.97 changed the message id length is read from Exim’s ChangeLog (entry JH/29), not observed on a running server.