From 1ac61eecb6ba12573c53c55c041c929c65342cdf Mon Sep 17 00:00:00 2001 From: DualFroz Date: Sat, 3 Oct 2026 01:37:31 +0200 Subject: [PATCH] Fold the To list passed to mail() mailSend() joined the To addresses for mail() with its own implode, so a long list still went out as one line, while the To header used for getSentMIMEMessage() and DKIM signing is folded by addrAppend(). mail() keeps CRLF + space folds in its to argument, so build it with addrAppend() too. --- src/PHPMailer.php | 3 ++- test/PHPMailer/MailTransportTest.php | 37 ++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/PHPMailer.php b/src/PHPMailer.php index 5ccf8ff..5a528d8 100644 --- a/src/PHPMailer.php +++ b/src/PHPMailer.php @@ -2090,7 +2090,8 @@ class PHPMailer foreach ($this->to as $toaddr) { $toArr[] = $this->addrFormat($toaddr); } - $to = trim(implode(', ', $toArr)); + //Fold long lists the same way as the To header, mail() keeps CRLF + WSP folds intact + $to = trim(substr($this->addrAppend('To', $this->to), strlen('To:'))); //If there are no To-addresses (e.g. when sending only to BCC-addresses) //the following should be added to get a correct DKIM-signature. diff --git a/test/PHPMailer/MailTransportTest.php b/test/PHPMailer/MailTransportTest.php index f557052..d506898 100644 --- a/test/PHPMailer/MailTransportTest.php +++ b/test/PHPMailer/MailTransportTest.php @@ -13,6 +13,7 @@ namespace PHPMailer\Test\PHPMailer; +use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\Test\SendTestCase; /** @@ -117,6 +118,42 @@ final class MailTransportTest extends SendTestCase self::assertStringNotContainsString("\r\n\r\nMIME-Version:", $msg, 'Incorrect MIME headers'); } + /** + * Test that a long To list is folded before it is passed to mail(). + * + * @covers \PHPMailer\PHPMailer\PHPMailer::mailSend + */ + public function testMailSendFoldsLongToList() + { + $this->Mail->Body = 'Sending via mail()'; + $this->buildBody(); + $this->Mail->Subject = $this->Mail->Subject . ': mail()'; + $this->Mail->clearAddresses(); + for ($i = 1; $i <= 100; ++$i) { + $this->Mail->addAddress('recipient' . $i . '@example.com', 'Recipient ' . $i); + } + + $to = ''; + $this->Mail->Debugoutput = static function ($str) use (&$to) { + if (strpos($str, 'To: ') === 0) { + $to = substr($str, 4); + } + }; + $this->Mail->isMail(); + self::assertTrue($this->Mail->send(), $this->Mail->ErrorInfo); + + $lines = explode(PHPMailer::getLE(), 'To: ' . $to); + self::assertGreaterThan(1, count($lines), 'The To list was not folded'); + foreach ($lines as $index => $line) { + self::assertLessThanOrEqual(PHPMailer::MAX_LINE_LENGTH, strlen($line), "Line $index is too long"); + } + self::assertStringContainsString( + 'To: ' . $to . PHPMailer::getLE(), + $this->Mail->getSentMIMEMessage(), + 'mail() did not get the same To list as the message header' + ); + } + /** * Test sending using PHP mail() function with Sender address * and explicit sendmail_from ini set.