I wrote the following bit of code to read through a passed in email stream (or .eml file while I’m testing).
During the test, it’s supposed to read through each line of a stream but it seems it’s just outputting as one line, even thouhg there is a newline in the stream.
My code is as follows:
function sendMailForward($email) {
// Load recipients from ENV (comma-separated list)
$newRecipients = preg_split("/,s*/", $_ENV['ADMIN_EMAIL'] ?? '', -1, PREG_SPLIT_NO_EMPTY);
// For StackOverflow: This passes in a comma-separated list of emails, this line is not part of the problem.
$raw_email = "";
while (!feof($email)) {
$raw_email .= fread($email, 1024);
}
fclose($email);
// Extract headers for a clean subject and sender
$headers = [];
$lines = explode("n", $raw_email); // This line, somehow, doesn't see newlines in the stream.
foreach ($lines as $line) {
echo "New line!n"; // This was me trying to test and what should show up multiple times, only shows up once.
if (strpos($line, ":") !== false) {
$parts = explode(":", $line, 2);
$key = trim($parts[0]);
$value = trim($parts[1]);
$headers[$key] = $value;
}
// Stop at the first blank line, which marks the end of headers
if (trim($line) == "") {
break;
}
}
$original_subject = isset($headers['Subject']) ? "FWD: " . $headers['Subject'] : "FWD: No Subject";
$original_from = isset($headers['From']) ? $headers['From'] : "unknown sender";
$subject = $original_subject;
$message = "--- Original message from $original_from ---nn" . $raw_email;
$extra_headers = "From: [email protected]"; // Customize 'From' address
foreach ($newRecipients as $recipient) {
$to = $recipient;
// Send the email
mail($to, $subject, $message, $extra_headers);
}
}
What should I change in the above code? Should I force a newline to be appended? Or is there something else happening that I should be aware of.
(If it also helps, the rest of the email is non-existent too.)
Per request below. This is the email I’m using to test.
From: "Megan at TCGplayer" <[email protected]>
To: "TCGPlayer Account" <[email protected]>
Subject: Test Email for Forwarding
Date: Sat, 28 Sep 2025 08:00:00 -0400
Message-ID: <[email protected]>
MIME-Version: 1.0
Content-Type: text/plain; charset="UTF-8"
Content-Transfer-Encoding: 7bit
Hello,
This is a test email to verify the mail forwarding module.
Best regards,
Test System
EDIT 2: Someone asked for how is the code being used.
// Read original message from stdin
$rawEmail = file_get_contents('php://stdin');
sendMailForward($rawEmail);
Simply put just invoking it.