PHPMailer via SMTP on MailGun fails with 451 malformed header error after several hundred emails

PHPMailer bulk sends encounter a 451 header parse error with MailGun after around 100 emails. Below is an alternative, concise PHP code example:

use PHPMailer\PHPMailer\Mailer;
use PHPMailer\PHPMailer\SMTP as MailerSMTP;
use PHPMailer\PHPMailer\MailerException;

require 'Mailer.php';
require 'MailerSMTP.php';
require 'MailerException.php';

$mailer = new Mailer(true);
$mailer->CharSet = 'utf-8';
$mailer->Encoding = 'base64';
$mailer->isSMTP();
$mailer->SMTPKeepAlive = true;
$mailer->Host = 'smtp.mailgun.org';
$mailer->Port = 587;
$mailer->SMTPAuth = true;
$mailer->Username = '[email protected]';
$mailer->Password = 'secret';
$mailer->SMTPSecure = 'tls';
$mailer->SMTPDebug = 0;

$mailer->setFrom('[email protected]', 'Your Brand');
$mailer->addReplyTo('[email protected]', 'Your Brand');
$mailer->addAddress('[email protected]', 'Recipient Name');
$mailer->isHTML(true);
$mailer->Subject = 'Bulk Email Test';

$mailer->Body = '<p>Testing bulk email via PHPMailer with MailGun SMTP using utf-8 and base64 encoding.</p>';
$mailer->AltBody = 'Testing bulk email via MailGun SMTP with PHPMailer.';

try {
    $mailer->send();
    echo 'Email sent successfully.';
} catch (MailerException $ex) {
    echo 'Email send failed: ' . $ex->getMessage();
}

hey, im having a simalar issue. i fixed it by closing the smtp connection every few sends to avoid header buildup. might be worth checking out