Commit 960d366b20 for wordpress.org

commit 960d366b20d0b083d7691080e0c5767ac50ac584
Author: SergeyBiryukov <sergeybiryukov@git.wordpress.org>
Date:   Fri Dec 4 23:55:01 2026 +0000

    External Libraries: Upgrade PHPMailer to version 7.4.1.

    This includes 7.3.0, a maintenance release, and 7.4.0, a security release. 7.4.1 has no code changes beyond 7.4.0. It only corrects the version constants that 7.4.0 missed.

    References:
    * [https://github.com/PHPMailer/PHPMailer/releases/tag/v7.4.1 PHPMailer 7.4.1 release notes]
    * [https://github.com/PHPMailer/PHPMailer/releases/tag/v7.4.0 PHPMailer 7.4.0 release notes]
    * [https://github.com/PHPMailer/PHPMailer/releases/tag/v7.3.0 PHPMailer 7.3.0 release notes]
    * [https://github.com/PHPMailer/PHPMailer/compare/v7.2.0...v7.4.1 Full list of changes in PHPMailer 7.2.0 → 7.4.1]

    Developed in https://github.com/WordPress/wordpress-develop/pull/16510.

    Follow-up to r54937, r55557, r56484, r57137, r59246, r59481, r60623, r60813, r60888, r61249, r61468, r62975, r65457.

    Props SirLouen.
    Fixes #66941.
    Built from https://develop.svn.wordpress.org/trunk@65936


    git-svn-id: http://core.svn.wordpress.org/trunk@64965 1a063a9b-81f0-0310-95a4-ce76da25c4cd

diff --git a/wp-includes/PHPMailer/DSNConfigurator.php b/wp-includes/PHPMailer/DSNConfigurator.php
index 9c855fa729..4a3502daa4 100644
--- a/wp-includes/PHPMailer/DSNConfigurator.php
+++ b/wp-includes/PHPMailer/DSNConfigurator.php
@@ -54,6 +54,9 @@ class DSNConfigurator

     /**
      * Configure PHPMailer instance with DSN string.
+     * Warning: *all* PHPMailer properties can be set through this mechanism,
+     * including those that have security consequences, so do not use
+     * user-provided DSN strings without strict validation of all parameters.
      *
      * @param PHPMailer $mailer PHPMailer instance
      * @param string    $dsn    DSN
@@ -157,11 +160,11 @@ class DSNConfigurator
         $mailer->SMTPAuth = isset($config['user']) || isset($config['pass']);

         if (isset($config['user'])) {
-            $mailer->Username = $config['user'];
+            $mailer->Username = rawurldecode($config['user']);
         }

         if (isset($config['pass'])) {
-            $mailer->Password = $config['pass'];
+            $mailer->Password = rawurldecode($config['pass']);
         }
     }

@@ -171,7 +174,7 @@ class DSNConfigurator
      * @param PHPMailer $mailer  PHPMailer instance
      * @param array     $options Options
      *
-     * @throws Exception If option is unknown
+     * @throws Exception If option is unknown, or a boolean option has an invalid value
      */
     private function configureOptions(PHPMailer $mailer, $options)
     {
@@ -206,7 +209,19 @@ class DSNConfigurator
                 case 'UseSendmailOptions':
                 case 'do_verp':
                 case 'DKIM_copyHeaderFields':
-                    $mailer->$key = (bool) $value;
+                    $boolean = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
+                    if (null === $boolean) {
+                        //Don't guess: a typo such as "ture" would otherwise silently become false
+                        throw new Exception(
+                            sprintf(
+                                'Invalid value for option "%s": "%s". Allowed values: "true", "false", "on", ' .
+                                '"off", "yes", "no", "1", "0"',
+                                $key,
+                                $value
+                            )
+                        );
+                    }
+                    $mailer->$key = $boolean;
                     break;
                 case 'Priority':
                 case 'SMTPDebug':
diff --git a/wp-includes/PHPMailer/OAuth.php b/wp-includes/PHPMailer/OAuth.php
index a7e958860c..2b80488fc3 100644
--- a/wp-includes/PHPMailer/OAuth.php
+++ b/wp-includes/PHPMailer/OAuth.php
@@ -123,9 +123,14 @@ class OAuth implements OAuthTokenProvider
      */
     public function getOauth64()
     {
-        //Get a new token if it's not available or has expired
+        //Get a new token if it's not available or has expired. Update the refresh token.
         if (null === $this->oauthToken || $this->oauthToken->hasExpired()) {
             $this->oauthToken = $this->getToken();
+            //Providers may not issue a new refresh token, in which case the current one remains valid
+            $refreshToken = $this->oauthToken->getRefreshToken();
+            if (!empty($refreshToken)) {
+                $this->oauthRefreshToken = $refreshToken;
+            }
         }

         return base64_encode(
@@ -136,4 +141,13 @@ class OAuth implements OAuthTokenProvider
             "\001\001"
         );
     }
+    /**
+     * Getter for the Refresh Token.
+     *
+     * @return string
+     */
+    public function getRefreshToken()
+    {
+        return $this->oauthRefreshToken;
+    }
 }
diff --git a/wp-includes/PHPMailer/PHPMailer.php b/wp-includes/PHPMailer/PHPMailer.php
index 5fc3208f58..84ad844eab 100644
--- a/wp-includes/PHPMailer/PHPMailer.php
+++ b/wp-includes/PHPMailer/PHPMailer.php
@@ -62,8 +62,18 @@ class PHPMailer
     const RFC822_DATE_FORMAT = 'D, j M Y H:i:s O';

     /**
-     * Email priority.
-     * Options: null (default), 1 = High, 3 = Normal, 5 = low.
+     * RFC 5322 atext characters, plus space and quoting characters.
+     *
+     * @var string
+     */
+    const PHRASE_ATOM_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!#$%&\'*+/=?^_`{|}~ -';
+
+    /**
+     * Message priority.
+     * This is mapped to the non-standard X-Priority header.
+     * @see https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
+     * Options: null (default), integer 1–5 where 1 = Highest, 3 = Normal, 5 = lowest.
+     * Any other value will result in the header being omitted.
      * When null, the header is not set at all.
      *
      * @var int|null
@@ -150,10 +160,10 @@ class PHPMailer

     /**
      * An iCal message part body.
-     * Only supported in simple alt or alt_inline message types
-     * To generate iCal event structures, use classes like EasyPeasyICS or iCalcreator.
+     * Only included in messages that have an AltBody.
+     * To generate iCal event structures, use a library such as spatie/icalendar-generator.
      *
-     * @see https://kigkonsult.se/iCalcreator/
+     * @see https://github.com/spatie/icalendar-generator
      *
      * @var string
      */
@@ -400,7 +410,7 @@ class PHPMailer
      * @see SMTP::DEBUG_CLIENT: Client messages
      * @see SMTP::DEBUG_SERVER: Client and server messages
      * @see SMTP::DEBUG_CONNECTION: As SERVER plus connection status
-     * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed
+     * @see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, includes unredacted credentials, rarely needed
      *
      * @see SMTP::$do_debug
      *
@@ -769,7 +779,7 @@ class PHPMailer
      *
      * @var string
      */
-    const VERSION = '7.2.0';
+    const VERSION = '7.4.1';

     /**
      * Error severity: message only, continue processing.
@@ -803,6 +813,14 @@ class PHPMailer
      */
     const FWS = ' ';

+    /**
+     * The character list trimmed by default.
+     * This matches the default charlist of trim(), rtrim(), and ltrim()
+     * before PHP 8.6, which added the form feed character (\f) to it.
+     * Passing this explicitly keeps behavior consistent across PHP versions.
+     */
+    const TRIM_CHARACTERS = " \n\r\t\v\x00";
+
     /**
      * SMTP RFC standard line ending; Carriage Return, Line Feed.
      *
@@ -952,8 +970,9 @@ class PHPMailer
                     str_replace(
                         "\n",
                         "\n                   \t                  ",
-                        trim($str)
-                    )
+                        trim($str, self::TRIM_CHARACTERS)
+                    ),
+                    self::TRIM_CHARACTERS
                 ),
                 "\n";
         }
@@ -998,7 +1017,7 @@ class PHPMailer
      */
     private function parseSendmailPath($sendmailPath)
     {
-        $sendmailPath = trim((string)$sendmailPath);
+        $sendmailPath = trim((string)$sendmailPath, self::TRIM_CHARACTERS);
         if ($sendmailPath === '') {
             return $sendmailPath;
         }
@@ -1143,7 +1162,7 @@ class PHPMailer
     {
         $pos = false;
         if ($address !== null) {
-            $address = trim($address);
+            $address = trim($address, self::TRIM_CHARACTERS);
             $pos = strrpos($address, '@');
         }
         if (false === $pos) {
@@ -1163,7 +1182,7 @@ class PHPMailer
             return false;
         }
         if ($name !== null && is_string($name)) {
-            $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+            $name = trim(preg_replace('/[\r\n]+/', '', $name), self::TRIM_CHARACTERS); //Strip breaks and trim
         } else {
             $name = '';
         }
@@ -1289,7 +1308,7 @@ class PHPMailer
      * Note that quotes in the name part are removed.
      *
      * @deprecated This method will be removed in the next major release of PHPMailer.
-     * @see https://www.andrew.cmu.edu/user/agreen1/testing/mrbs/web/Mail/RFC822.php A more careful implementation
+     * @see https://github.com/pear/Mail/blob/master/Mail/RFC822.php A more careful implementation
      *
      * @param string $addrstr The address list string
      * @param bool|null $useimap Deprecated in PHPMailer 6.11.0.
@@ -1343,7 +1362,7 @@ class PHPMailer
     /**
      * Parse a string containing one or more RFC822-style comma-separated email addresses
      * with the form "display name <address>" into an array of name/address pairs.
-     * Uses a simpler parser that does not require the IMAP extension but doesnt support
+     * Uses a simpler parser that does not require the IMAP extension but doesn't support
      * the full RFC822 spec. For full RFC822 support, use the PHP IMAP extension.
      *
      * @param string $addrstr The address list string
@@ -1353,13 +1372,10 @@ class PHPMailer
      */
     protected static function parseSimplerAddresses($addrstr, $charset)
     {
-        // Emit a runtime notice to recommend using the IMAP extension for full RFC822 parsing
-        trigger_error(self::lang('imap_recommended'), E_USER_NOTICE);
-
         $addresses = [];
         $list = explode(',', $addrstr);
         foreach ($list as $address) {
-            $address = trim($address);
+            $address = trim($address, self::TRIM_CHARACTERS);
             //Is there a separate name part?
             if (strpos($address, '<') === false) {
                 //No separate name, just use the whole thing
@@ -1396,7 +1412,7 @@ class PHPMailer
      */
     private static function parseEmailString($input)
     {
-        $input = trim((string)$input);
+        $input = trim((string)$input, self::TRIM_CHARACTERS);

         if ($input === '') {
             return ['name' => '', 'email' => ''];
@@ -1413,10 +1429,10 @@ class PHPMailer
                 $name = $matches[2];
             // Simplest scenario, name and email are in the format "Name <email>".
             } elseif (isset($matches[3])) {
-                $name = trim($matches[3]);
+                $name = trim($matches[3], self::TRIM_CHARACTERS);
             }

-            return ['name' => $name, 'email' => trim($matches[4])];
+            return ['name' => $name, 'email' => trim($matches[4], self::TRIM_CHARACTERS)];
         }

         return ['name' => '', 'email' => $input];
@@ -1439,8 +1455,8 @@ class PHPMailer
             //Helps avoid a deprecation warning in the preg_replace() below
             $name = '';
         }
-        $address = trim((string)$address);
-        $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+        $address = trim((string)$address, self::TRIM_CHARACTERS);
+        $name = trim(preg_replace('/[\r\n]+/', '', $name), self::TRIM_CHARACTERS); //Strip breaks and trim
         //Don't validate now addresses with IDN. Will be done in send().
         $pos = strrpos($address, '@');
         if (
@@ -1622,10 +1638,17 @@ class PHPMailer
             static::idnSupported()
         ) {
             $domain = substr($address, ++$pos);
+            $charset = $this->CharSet;
+            if (
+                strtolower($charset) === self::CHARSET_ISO88591 &&
+                mb_check_encoding($domain, self::CHARSET_UTF8)
+            ) {
+                $charset = self::CHARSET_UTF8;
+            }
             //Verify CharSet string is a valid one, and domain properly encoded in this CharSet.
-            if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $this->CharSet)) {
+            if ($this->has8bitChars($domain) && @mb_check_encoding($domain, $charset)) {
                 //Convert the domain from whatever charset it's in to UTF-8
-                $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $this->CharSet);
+                $domain = mb_convert_encoding($domain, self::CHARSET_UTF8, $charset);
                 //Ignore IDE complaints about this line - method signature changed in PHP 5.4
                 $errorcode = 0;
                 if (defined('INTL_IDNA_VARIANT_UTS46')) {
@@ -1720,7 +1743,7 @@ class PHPMailer
             //while remaining compatible with legacy SMTP servers to
             //the greatest degree possible: If the message uses
             //Unicode in the local parts of any addresses, it is sent
-            //using SMTPUTF8. If not, it it sent using
+            //using SMTPUTF8. If not, it is sent using
             //punycode-encoded domains and plain SMTP.
             if (
                 static::CHARSET_UTF8 === strtolower($this->CharSet) &&
@@ -1748,7 +1771,7 @@ class PHPMailer
                     $this->{$address_kind} = '';
                     continue;
                 }
-                $this->{$address_kind} = trim($this->{$address_kind});
+                $this->{$address_kind} = trim($this->{$address_kind}, self::TRIM_CHARACTERS);
                 if (empty($this->{$address_kind})) {
                     continue;
                 }
@@ -1777,13 +1800,12 @@ class PHPMailer

             $this->setMessageType();
             //Refuse to send an empty message unless we are specifically allowing it
-            if (!$this->AllowEmpty && empty($this->Body)) {
+            if (!$this->AllowEmpty && empty($this->Body) && '0' !== $this->Body) {
                 throw new Exception(self::lang('empty_message'), self::STOP_CRITICAL);
             }

             //Trim subject consistently
-            $this->Subject = trim($this->Subject);
-
+            $this->Subject = trim($this->Subject, self::TRIM_CHARACTERS);

             //Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
             $this->MIMEHeader = '';
@@ -1807,7 +1829,13 @@ class PHPMailer
                 );
             }

-            //Sign with DKIM if enabled
+            //Sign with DKIM if enabled and params are valid
+            if (!static::isValidHost($this->DKIM_domain)) {
+                $this->DKIM_domain = '';
+            }
+            if (!$this->validateDKIMSelector($this->DKIM_selector)) {
+                $this->DKIM_selector = '';
+            }
             if (
                 !empty($this->DKIM_domain)
                 && !empty($this->DKIM_selector)
@@ -1932,7 +1960,7 @@ class PHPMailer

         $resultArgs = (empty($sendmailArgs) ? '' : ' ' . implode(' ', $sendmailArgs));

-        $sendmail = trim(escapeshellcmd($this->Sendmail) . $resultArgs);
+        $sendmail = trim(escapeshellcmd($this->Sendmail) . $resultArgs, self::TRIM_CHARACTERS);
         $this->edebug('Sendmail path: ' . $this->Sendmail);
         $this->edebug('Sendmail command: ' . $sendmail);
         $this->edebug('Envelope sender: ' . $this->Sender);
@@ -2091,7 +2119,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:')), self::TRIM_CHARACTERS);

         //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.
@@ -2370,11 +2399,11 @@ class PHPMailer
             if (
                 !preg_match(
                     '/^(?:(ssl|tls):\/\/)?(.+?)(?::(\d+))?$/',
-                    trim($hostentry),
+                    trim($hostentry, self::TRIM_CHARACTERS),
                     $hostinfo
                 )
             ) {
-                $this->edebug(self::lang('invalid_hostentry') . ' ' . trim($hostentry));
+                $this->edebug(self::lang('invalid_hostentry') . ' ' . trim($hostentry, self::TRIM_CHARACTERS));
                 //Not a valid host entry
                 continue;
             }
@@ -2458,7 +2487,7 @@ class PHPMailer
                             $this->oauth
                         )
                     ) {
-                        throw new Exception(self::lang('authenticate'));
+                        throw new Exception($this->getSmtpErrorMessage('authenticate'));
                     }

                     return true;
@@ -2695,8 +2724,12 @@ class PHPMailer
             return $this->secureHeader($addr[0]);
         }

-        return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') .
-            ' <' . $this->secureHeader($addr[0]) . '>';
+        $name = $this->encodeHeader($this->secureHeader($addr[1]), 'phrase');
+        if ('' === $name) { //Nothing left after removing control characters
+            return $this->secureHeader($addr[0]);
+        }
+
+        return $name . ' <' . $this->secureHeader($addr[0]) . '>';
     }

     /**
@@ -2772,6 +2805,11 @@ class PHPMailer
                         } elseif ('=' === substr($word, $len - 2, 1)) {
                             $len -= 2;
                         }
+                        if ($len < 1) {
+                            //A run of continuation bytes as long as the line has no character boundary to
+                            //break at; break at the full length, otherwise this loop never ends
+                            $len = $length;
+                        }
                         $part = substr($word, 0, $len);
                         $word = (string) substr($word, $len);

@@ -2839,6 +2877,10 @@ class PHPMailer
                 } elseif ($dec < 192) {
                     //Middle byte of a multi byte character, look further back
                     $lookBack += 3;
+                    if ($lookBack > $maxLength) {
+                        //No character starts within the line, so there is no boundary to split at
+                        return 0;
+                    }
                 }
             } else {
                 //No encoded character found
@@ -2891,6 +2933,9 @@ class PHPMailer
         //The To header is created automatically by mail(), so needs to be omitted here
         if ('mail' !== $this->Mailer) {
             if ($this->SingleTo) {
+                //Rebuild the list on every call, otherwise recipients from earlier messages
+                //(or from earlier calls for the same message) would be sent to again
+                $this->SingleToArray = [];
                 foreach ($this->to as $toaddr) {
                     $this->SingleToArray[] = $this->addrFormat($toaddr);
                 }
@@ -2900,7 +2945,7 @@ class PHPMailer
                 $result .= $this->headerLine('To', 'undisclosed-recipients:;');
             }
         }
-        $result .= $this->addrAppend('From', [[trim($this->From), $this->FromName]]);
+        $result .= $this->addrAppend('From', [[trim($this->From, self::TRIM_CHARACTERS), $this->FromName]]);

         //sendmail and mail() extract Cc from the header before sending
         if (count($this->cc) > 0) {
@@ -2944,6 +2989,7 @@ class PHPMailer
             $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->serverHostname());
         }
         $result .= $this->headerLine('Message-ID', $this->lastMessageID);
+        $this->Priority = self::sanitisePriority($this->Priority);
         if (null !== $this->Priority) {
             $result .= $this->headerLine('X-Priority', $this->Priority);
         }
@@ -2953,9 +2999,9 @@ class PHPMailer
                 'X-Mailer',
                 'PHPMailer ' . self::VERSION . ' (https://github.com/PHPMailer/PHPMailer)'
             );
-        } elseif (is_string($this->XMailer) && trim($this->XMailer) !== '') {
+        } elseif (is_string($this->XMailer) && trim($this->XMailer, self::TRIM_CHARACTERS) !== '') {
             //Some string
-            $result .= $this->headerLine('X-Mailer', $this->secureHeader(trim($this->XMailer)));
+            $result .= $this->headerLine('X-Mailer', $this->secureHeader(trim($this->XMailer, self::TRIM_CHARACTERS)));
         } //Other values result in no X-Mailer header

         if ('' !== $this->ConfirmReadingTo) {
@@ -2965,8 +3011,8 @@ class PHPMailer
         //Add custom headers
         foreach ($this->CustomHeader as $header) {
             $result .= $this->headerLine(
-                trim($header[0]),
-                $this->encodeHeader(trim($header[1]))
+                trim($header[0], self::TRIM_CHARACTERS),
+                $this->encodeHeader(trim($header[1], self::TRIM_CHARACTERS))
             );
         }
         if (!$this->sign_key_file) {
@@ -3181,20 +3227,7 @@ class PHPMailer
                 $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= static::$LE;
                 if (!empty($this->Ical)) {
-                    $method = static::ICAL_METHOD_REQUEST;
-                    foreach (static::$IcalMethods as $imethod) {
-                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
-                            $method = $imethod;
-                            break;
-                        }
-                    }
-                    $body .= $this->getBoundary(
-                        $this->boundary[1],
-                        '',
-                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
-                        ''
-                    );
-                    $body .= $this->encodeString($this->Ical, $this->Encoding);
+                    $body .= $this->getIcalPart($this->boundary[1]);
                     $body .= static::$LE;
                 }
                 $body .= $this->endBoundary($this->boundary[1]);
@@ -3224,6 +3257,10 @@ class PHPMailer
                 $body .= static::$LE;
                 $body .= $this->attachAll('inline', $this->boundary[2]);
                 $body .= static::$LE;
+                if (!empty($this->Ical)) {
+                    $body .= $this->getIcalPart($this->boundary[1]);
+                    $body .= static::$LE;
+                }
                 $body .= $this->endBoundary($this->boundary[1]);
                 break;
             case 'alt_attach':
@@ -3249,20 +3286,7 @@ class PHPMailer
                 $body .= $this->encodeString($this->Body, $bodyEncoding);
                 $body .= static::$LE;
                 if (!empty($this->Ical)) {
-                    $method = static::ICAL_METHOD_REQUEST;
-                    foreach (static::$IcalMethods as $imethod) {
-                        if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
-                            $method = $imethod;
-                            break;
-                        }
-                    }
-                    $body .= $this->getBoundary(
-                        $this->boundary[2],
-                        '',
-                        static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
-                        ''
-                    );
-                    $body .= $this->encodeString($this->Ical, $this->Encoding);
+                    $body .= $this->getIcalPart($this->boundary[2]);
                 }
                 $body .= $this->endBoundary($this->boundary[2]);
                 $body .= static::$LE;
@@ -3297,6 +3321,10 @@ class PHPMailer
                 $body .= static::$LE;
                 $body .= $this->attachAll('inline', $this->boundary[3]);
                 $body .= static::$LE;
+                if (!empty($this->Ical)) {
+                    $body .= $this->getIcalPart($this->boundary[2]);
+                    $body .= static::$LE;
+                }
                 $body .= $this->endBoundary($this->boundary[2]);
                 $body .= static::$LE;
                 $body .= $this->attachAll('attachment', $this->boundary[1]);
@@ -3415,6 +3443,32 @@ class PHPMailer
         return $result;
     }

+    /**
+     * Return the iCal part of a multipart/alternative message: its boundary, headers and encoded body.
+     * The method in the Content-Type header is taken from the METHOD property of the iCal body.
+     *
+     * @param string $boundary
+     *
+     * @return string
+     */
+    protected function getIcalPart($boundary)
+    {
+        $method = static::ICAL_METHOD_REQUEST;
+        foreach (static::$IcalMethods as $imethod) {
+            if (stripos($this->Ical, 'METHOD:' . $imethod) !== false) {
+                $method = $imethod;
+                break;
+            }
+        }
+
+        return $this->getBoundary(
+            $boundary,
+            '',
+            static::CONTENT_TYPE_TEXT_CALENDAR . '; method=' . $method,
+            ''
+        ) . $this->encodeString($this->Ical, $this->Encoding);
+    }
+
     /**
      * Return the end of a message boundary.
      *
@@ -3602,14 +3656,14 @@ class PHPMailer
                 if (!empty($name)) {
                     $mime[] = sprintf(
                         'Content-Type: %s; name=%s%s',
-                        $type,
+                        static::secureHeader($type),
                         static::quotedString($this->encodeHeader($this->secureHeader($name))),
                         static::$LE
                     );
                 } else {
                     $mime[] = sprintf(
                         'Content-Type: %s%s',
-                        $type,
+                        static::secureHeader($type),
                         static::$LE
                     );
                 }
@@ -3742,6 +3796,26 @@ class PHPMailer
         return $encoded;
     }

+    /**
+     * Quote and escape a string for use as an RFC 5322 phrase (for example,
+     * an address display name), without encoding it.
+     *
+     * @param string $str The string to quote
+     *
+     * @return string
+     */
+    private static function quotePhrase($str)
+    {
+        //Escape just the characters that need it in a quoted-string: backslash and double quote;
+        //control characters have already been stripped by the caller
+        $encoded = addcslashes($str, "\\\"");
+        if (($str === $encoded) && strlen($str) === strspn($str, self::PHRASE_ATOM_CHARS)) {
+            return $encoded;
+        }
+
+        return "\"$encoded\"";
+    }
+
     /**
      * Encode a header value (not including its label) optimally.
      * Picks shortest of Q, B, or none. Result includes folding if needed.
@@ -3756,21 +3830,36 @@ class PHPMailer
     public function encodeHeader($str, $position = 'text')
     {
         $position = strtolower($position);
+        if ('phrase' === $position) {
+            //RFC 5322 only allows control characters in a display name in its obsolete syntax, which must not be
+            //generated, so strip them; tab is allowed. ESC is kept for 7-bit charsets such as ISO-2022-JP,
+            //which use it in their escape sequences.
+            $str = preg_replace(
+                $this->is7bitStatefulCharset() ? '/[\000-\010\012-\032\034-\037\177]/' : '/[\000-\010\012-\037\177]/',
+                '',
+                $str
+            );
+        }
         if ($this->UseSMTPUTF8 && !("comment" === $position)) {
-            return trim(static::normalizeBreaks($str));
+            //Sending unencoded UTF-8 is legal when SMTPUTF8 is used.
+            //The phrase position has already been sanitised above, so the raw
+            //text can be returned for all positions except comment.
+            if ('phrase' === $position) {
+                //Under SMTPUTF8, RFC 6532 permits raw UTF-8 in a quoted string,
+                //so quote rather than Q/B-encode; the phrase must still be
+                //quoted and escaped to prevent address-list injection.
+                return self::quotePhrase($str);
+            }
+
+            return trim(static::normalizeBreaks($str), self::TRIM_CHARACTERS);
         }

         $matchcount = 0;
-        switch (strtolower($position)) {
+        switch ($position) {
             case 'phrase':
-                if (!preg_match('/[\200-\377]/', $str)) {
-                    //Can't use addslashes as we don't know the value of magic_quotes_sybase
-                    $encoded = addcslashes($str, "\0..\37\177\\\"");
-                    if (($str === $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
-                        return $encoded;
-                    }
-
-                    return "\"$encoded\"";
+                //A tab can stay in a quoted-string; ESC is only left for 7-bit stateful charsets, which need encoding
+                if (!preg_match('/[\033\200-\377]/', $str)) {
+                    return self::quotePhrase($str);
                 }
                 $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
                 break;
@@ -3784,7 +3873,9 @@ class PHPMailer
                 break;
         }

-        if ($this->has8bitChars($str)) {
+        //7-bit charsets such as ISO-2022-JP or UTF-7 write non-ASCII text with ASCII bytes,
+        //so only an ASCII-compatible charset can be relabelled as us-ascii
+        if ($this->has8bitChars($str) || $this->is7bitStatefulCharset()) {
             $charset = $this->CharSet;
         } else {
             $charset = static::CHARSET_ASCII;
@@ -3823,21 +3914,21 @@ class PHPMailer
                 } else {
                     $encoded = base64_encode($str);
                     $maxlen -= $maxlen % 4;
-                    $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
+                    $encoded = trim(chunk_split($encoded, $maxlen, "\n"), self::TRIM_CHARACTERS);
                 }
                 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
                 break;
             case 'Q':
                 $encoded = $this->encodeQ($str, $position);
                 $encoded = $this->wrapText($encoded, $maxlen, true);
-                $encoded = str_replace('=' . static::$LE, "\n", trim($encoded));
+                $encoded = str_replace('=' . static::$LE, "\n", trim($encoded, self::TRIM_CHARACTERS));
                 $encoded = preg_replace('/^(.*)$/m', ' =?' . $charset . "?$encoding?\\1?=", $encoded);
                 break;
             default:
                 return $str;
         }

-        return trim(static::normalizeBreaks($encoded));
+        return trim(static::normalizeBreaks($encoded), self::TRIM_CHARACTERS);
     }

     /**
@@ -3893,6 +3984,17 @@ class PHPMailer
         return false;
     }

+    /**
+     * Is the message charset a 7-bit charset such as ISO-2022-JP or UTF-7, which writes non-ASCII text
+     * with ASCII bytes and so can't be relabelled as us-ascii?
+     *
+     * @return bool
+     */
+    protected function is7bitStatefulCharset()
+    {
+        return (bool) preg_match('/^(iso-2022-|utf-7|hz-gb-2312)/i', $this->CharSet);
+    }
+
     /**
      * Does a string contain any 8-bit chars (in any charset)?
      *
@@ -4392,8 +4494,8 @@ class PHPMailer
             //Value passed in as name:value
             list($name, $value) = explode(':', $name, 2);
         }
-        $name = trim($name);
-        $value = (null === $value) ? null : trim($value);
+        $name = trim($name, self::TRIM_CHARACTERS);
+        $value = (null === $value) ? null : trim($value, self::TRIM_CHARACTERS);

         foreach ($this->CustomHeader as $k => $pair) {
             if ($pair[0] == $name) {
@@ -4424,8 +4526,8 @@ class PHPMailer
             //Value passed in as name:value
             list($name, $value) = explode(':', $name, 2);
         }
-        $name = trim($name);
-        $value = (null === $value) ? '' : trim($value);
+        $name = trim($name, self::TRIM_CHARACTERS);
+        $value = (null === $value) ? '' : trim($value, self::TRIM_CHARACTERS);

         $replaced = false;
         foreach ($this->CustomHeader as $k => $pair) {
@@ -4533,6 +4635,23 @@ class PHPMailer
         }
     }

+    /**
+     * Sanitise and validate an X-Priority header value.
+     * @see https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxcmail/2bb19f1b-b35e-4966-b1cb-1afd044e83ab
+     *
+     * @param $priority
+     *
+     * @return int|null
+     */
+    private static function sanitisePriority($priority)
+    {
+        if ($priority === null || (is_int($priority) && $priority >= 1 && $priority <= 5)) {
+            return $priority;
+        }
+
+        return null;
+    }
+
     /**
      * Get the server hostname.
      * Returns 'localhost.localdomain' if unknown.
@@ -4587,10 +4706,42 @@ class PHPMailer
             //Is it a valid IPv4 address?
             return filter_var($host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false;
         }
+        //Empty labels are invalid, but some PHP versions' URL validation accepts them
+        if (strpos($host, '..') !== false || $host[0] === '.') {
+            return false;
+        }
         //Is it a syntactically valid hostname (when embedded in a URL)?
         return filter_var('https://' . $host, FILTER_VALIDATE_URL) !== false;
     }

+    /**
+     * Validate a DKIM selector.
+     * RFC 6376 defers to RFC5321's `Domain` ABNF syntax for the selector,
+     * which is a series of one or more dot-separated `sub-domain`s.
+     * Underscores are allowed as `atext` characters, as selectors are
+     * commonly served from the `_domainkey` sub-domain.
+     * @see https://www.rfc-editor.org/info/rfc6376/#section-3.1
+     * @see https://www.rfc-editor.org/info/rfc5321/#section-4.1.2
+     * UTF-8 is supported indirectly through punyencode
+     *
+     * @param string $selector
+     *
+     * @return bool
+     */
+    protected function validateDKIMSelector($selector)
+    {
+        if (is_string($selector) && $this->has8bitChars($selector)) {
+            $selector = $this->punyencodeAddress($selector);
+        }
+
+        return is_string($selector)
+            && $selector !== ''
+            && preg_match(
+                '/^[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?(?:\.[A-Za-z0-9_](?:[A-Za-z0-9_-]*[A-Za-z0-9_])?)*$/',
+                $selector
+            );
+    }
+
     /**
      * Check whether the supplied address uses Unicode in the local part.
      *
@@ -4629,7 +4780,6 @@ class PHPMailer
         return $this->UseSMTPUTF8;
     }

-
     /**
      * Get an error message in the current language.
      *
@@ -4705,8 +4855,8 @@ class PHPMailer
             //Value passed in as name:value
             list($name, $value) = explode(':', $name, 2);
         }
-        $name = trim($name);
-        $value = (null === $value) ? '' : trim($value);
+        $name = trim($name, self::TRIM_CHARACTERS);
+        $value = (null === $value) ? '' : trim($value, self::TRIM_CHARACTERS);
         //Ensure name is not empty, and that neither name nor value contain line breaks
         if (empty($name) || strpbrk($name . $value, "\r\n") !== false) {
             if ($this->exceptions) {
@@ -4738,11 +4888,14 @@ class PHPMailer
      * $basedir is prepended when handling relative URLs, e.g. <img src="/images/a.png"> and must not be empty
      * will look for an image file in $basedir/images/a.png and convert it to inline.
      * If you don't provide a $basedir, relative paths will be left untouched (and thus probably break in email)
+     * Instead of a directory, $basedir can be a callable that receives each relative URL and returns
+     * an array with the image `data`, and optionally its `name` and MIME `type`, or null to leave the URL untouched.
      * Converts data-uri images into embedded attachments.
      * If you don't want to apply these transformations to your HTML, just set Body and AltBody directly.
      *
      * @param string        $message    HTML message string
-     * @param string        $basedir    Absolute path to a base directory to prepend to relative paths to images
+     * @param string|callable $basedir  Absolute path to a base directory to prepend to relative paths to images,
+     *                                  or a callable that returns the image for a relative URL
      * @param bool|callable $advanced   Whether to use the internal HTML to text converter
      *                                  or your own custom converter
      * @return string The transformed message body
@@ -4761,6 +4914,11 @@ class PHPMailer

         preg_match_all('/(?<!-)(src|background)=["\'](.*)["\']/Ui', $message, $images);
         if (array_key_exists(2, $images)) {
+            $resolver = null;
+            if (!is_string($basedir) && is_callable($basedir)) {
+                $resolver = $basedir;
+                $basedir = '';
+            }
             if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
                 //Ensure $basedir has a trailing /
                 $basedir .= '/';
@@ -4799,8 +4957,8 @@ class PHPMailer
                     continue;
                 }
                 if (
-                    //Only process relative URLs if a basedir is provided (i.e. no absolute local paths)
-                    !empty($basedir)
+                    //Only process relative URLs if a basedir or resolver is provided (i.e. no absolute local paths)
+                    (!empty($basedir) || null !== $resolver)
                     //Ignore URLs containing parent dir traversal (..)
                     && (strpos($url, '..') === false)
                     //Do not change urls that are already inline images
@@ -4815,21 +4973,34 @@ class PHPMailer
                     }
                     //RFC2392 S 2
                     $cid = substr(hash('sha256', $url), 0, 32) . '@' . $cid_domain;
-                    if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
-                        $basedir .= '/';
-                    }
-                    if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
-                        $directory .= '/';
-                    }
-                    if (
-                        $this->addEmbeddedImage(
+                    if (null !== $resolver) {
+                        $image = $resolver($url);
+                        $added = is_array($image) && isset($image['data'])
+                            && $this->addStringEmbeddedImage(
+                                $image['data'],
+                                $cid,
+                                isset($image['name']) ? $image['name'] : $filename,
+                                static::ENCODING_BASE64,
+                                isset($image['type']) ? $image['type'] : static::_mime_types(
+                                    (string) static::mb_pathinfo($filename, PATHINFO_EXTENSION)
+                                )
+                            );
+                    } else {
+                        if (strlen($basedir) > 1 && '/' !== substr($basedir, -1)) {
+                            $basedir .= '/';
+                        }
+                        if (strlen($directory) > 1 && '/' !== substr($directory, -1)) {
+                            $directory .= '/';
+                        }
+                        $added = $this->addEmbeddedImage(
                             $basedir . $directory . $filename,
                             $cid,
                             $filename,
                             static::ENCODING_BASE64,
                             static::_mime_types((string) static::mb_pathinfo($filename, PATHINFO_EXTENSION))
-                        )
-                    ) {
+                        );
+                    }
+                    if ($added) {
                         $message = preg_replace(
                             '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
                             $images[1][$imgindex] . '="cid:' . $cid . '"',
@@ -4881,8 +5052,22 @@ class PHPMailer
             return call_user_func($advanced, $html);
         }

+        //Drop the entire head section before stripping tags; its content is not useful in plain text.
+        //An earlier implementation also removed in-body script and style tags,
+        //but they are not valid, so not our problem; use the `$advanced` option if you want more control.
+        $headEnd = stripos($html, '</head>');
+        if (false !== $headEnd) {
+            $html = substr($html, $headEnd + strlen('</head>'));
+        }
+        //Likewise, drop anything after the end of the body section, which is
+        //where trailing script tags may lurk.
+        $bodyEnd = stripos($html, '</body>');
+        if (false !== $bodyEnd) {
+            $html = substr($html, 0, $bodyEnd);
+        }
+
         return html_entity_decode(
-            trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
+            trim(strip_tags($html), self::TRIM_CHARACTERS),
             ENT_QUOTES,
             $this->CharSet
         );
@@ -5123,7 +5308,7 @@ class PHPMailer
      */
     public function secureHeader($str)
     {
-        return trim(str_replace(["\r", "\n"], '', $str));
+        return trim(str_replace(["\r", "\n"], '', $str), self::TRIM_CHARACTERS);
     }

     /**
@@ -5462,7 +5647,18 @@ class PHPMailer
         //Base64 of packed binary SHA-256 hash of body
         $DKIMb64 = base64_encode(pack('H*', hash('sha256', $body)));
         $ident = '';
-        if ('' !== $this->DKIM_identity) {
+        if (
+            '' !== $this->DKIM_identity &&
+            (
+                //Identity can be an email address
+                self::validateAddress($this->DKIM_identity) ||
+                (
+                    //Or it can be a domain name, prefixed with @
+                    '@' === $this->DKIM_identity[0] &&
+                    self::isValidHost(substr($this->DKIM_identity, 1))
+                )
+            )
+        ) {
             $ident = ' i=' . $this->DKIM_identity . ';' . static::$LE;
         }
         //The DKIM-Signature header is included in the signature *except for* the value of the `b` tag
@@ -5485,7 +5681,10 @@ class PHPMailer
             $headerValues . static::$LE . $dkimSignatureHeader
         );
         $signature = $this->DKIM_Sign($canonicalizedHeaders);
-        $signature = trim(chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS));
+        $signature = trim(
+            chunk_split($signature, self::STD_LINE_LENGTH - 3, static::$LE . self::FWS),
+            self::TRIM_CHARACTERS
+        );

         return static::normalizeBreaks($dkimSignatureHeader . $signature);
     }
@@ -5505,7 +5704,7 @@ class PHPMailer

     /**
      * If a string contains any "special" characters, double-quote the name,
-     * and escape any double quotes with a backslash.
+     * and escape any double quotes and backslashes with a backslash.
      *
      * @param string $str
      *
@@ -5515,10 +5714,10 @@ class PHPMailer
      */
     public static function quotedString($str)
     {
-        if (preg_match('/[ ()<>@,;:"\/\[\]?=]/', $str)) {
+        if (preg_match('/[ ()<>@,;:"\/\[\]?=\\\\]/', $str)) {
             //If the string contains any of these chars, it must be double-quoted
-            //and any double quotes must be escaped with a backslash
-            return '"' . str_replace('"', '\\"', $str) . '"';
+            //and any double quotes or backslashes must be escaped with a backslash
+            return '"' . addcslashes($str, '\\"') . '"';
         }

         //Return the string untouched, it doesn't need quoting
@@ -5527,57 +5726,121 @@ class PHPMailer

     /**
      * Allows for public read access to 'to' property.
-     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
+     * Before the send() call, queued addresses (i.e. with IDN) are not yet included,
+     * unless $includeQueued is true; queued addresses are returned as they were added,
+     * without punycode conversion.
+     *
+     * @param bool $includeQueued Whether to include addresses queued until send()
      *
      * @return array
      */
-    public function getToAddresses()
+    public function getToAddresses($includeQueued = false)
     {
-        return $this->to;
+        if (!$includeQueued) {
+            return $this->to;
+        }
+
+        return $this->mergeQueuedAddresses($this->to, $this->RecipientsQueue, 'to');
     }

     /**
      * Allows for public read access to 'cc' property.
-     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
+     * Before the send() call, queued addresses (i.e. with IDN) are not yet included,
+     * unless $includeQueued is true; queued addresses are returned as they were added,
+     * without punycode conversion.
+     *
+     * @param bool $includeQueued Whether to include addresses queued until send()
      *
      * @return array
      */
-    public function getCcAddresses()
+    public function getCcAddresses($includeQueued = false)
     {
-        return $this->cc;
+        if (!$includeQueued) {
+            return $this->cc;
+        }
+
+        return $this->mergeQueuedAddresses($this->cc, $this->RecipientsQueue, 'cc');
     }

     /**
      * Allows for public read access to 'bcc' property.
-     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
+     * Before the send() call, queued addresses (i.e. with IDN) are not yet included,
+     * unless $includeQueued is true; queued addresses are returned as they were added,
+     * without punycode conversion.
+     *
+     * @param bool $includeQueued Whether to include addresses queued until send()
      *
      * @return array
      */
-    public function getBccAddresses()
+    public function getBccAddresses($includeQueued = false)
     {
-        return $this->bcc;
+        if (!$includeQueued) {
+            return $this->bcc;
+        }
+
+        return $this->mergeQueuedAddresses($this->bcc, $this->RecipientsQueue, 'bcc');
     }

     /**
      * Allows for public read access to 'ReplyTo' property.
-     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
+     * Before the send() call, queued addresses (i.e. with IDN) are not yet included,
+     * unless $includeQueued is true; queued addresses are returned as they were added,
+     * without punycode conversion.
+     *
+     * @param bool $includeQueued Whether to include addresses queued until send()
      *
      * @return array
      */
-    public function getReplyToAddresses()
+    public function getReplyToAddresses($includeQueued = false)
     {
-        return $this->ReplyTo;
+        if (!$includeQueued) {
+            return $this->ReplyTo;
+        }
+
+        return $this->mergeQueuedAddresses($this->ReplyTo, $this->ReplyToQueue, 'Reply-To');
     }

     /**
      * Allows for public read access to 'all_recipients' property.
-     * Before the send() call, queued addresses (i.e. with IDN) are not yet included.
+     * Before the send() call, queued addresses (i.e. with IDN) are not yet included,
+     * unless $includeQueued is true; queued addresses are returned as they were added,
+     * without punycode conversion.
+     *
+     * @param bool $includeQueued Whether to include addresses queued until send()
+     *
+     * @return array
+     */
+    public function getAllRecipientAddresses($includeQueued = false)
+    {
+        if (!$includeQueued) {
+            return $this->all_recipients;
+        }
+        $recipients = $this->all_recipients;
+        foreach ($this->RecipientsQueue as $params) {
+            $recipients[strtolower($params[1])] = true;
+        }
+
+        return $recipients;
+    }
+
+    /**
+     * Append the queued addresses of one kind to a list of [address, name] pairs.
+     *
+     * @param array  $addresses List of [address, name] pairs
+     * @param array  $queue     A queue of [kind, address, name] entries
+     * @param string $kind      One of 'to', 'cc', 'bcc', or 'Reply-To'
      *
      * @return array
      */
-    public function getAllRecipientAddresses()
+    protected function mergeQueuedAddresses(array $addresses, array $queue, $kind)
     {
-        return $this->all_recipients;
+        foreach ($queue as $params) {
+            if ($params[0] === $kind) {
+                $addresses[] = [$params[1], $params[2]];
+            }
+        }
+
+        return $addresses;
     }

     /**
diff --git a/wp-includes/PHPMailer/POP3.php b/wp-includes/PHPMailer/POP3.php
index 823ec8be3d..3c53b8e094 100644
--- a/wp-includes/PHPMailer/POP3.php
+++ b/wp-includes/PHPMailer/POP3.php
@@ -47,7 +47,7 @@ class POP3
      * @var string
      * @deprecated This constant will be removed in PHPMailer 8.0. Use `PHPMailer::VERSION` instead.
      */
-    const VERSION = '7.2.0';
+    const VERSION = '7.4.1';

     /**
      * Default POP3 port number.
diff --git a/wp-includes/PHPMailer/SMTP.php b/wp-includes/PHPMailer/SMTP.php
index 605d136b15..1005ae0bcd 100644
--- a/wp-includes/PHPMailer/SMTP.php
+++ b/wp-includes/PHPMailer/SMTP.php
@@ -36,7 +36,7 @@ class SMTP
      * @var string
      * @deprecated This constant will be removed in PHPMailer 8.0. Use `PHPMailer::VERSION` instead.
      */
-    const VERSION = '7.2.0';
+    const VERSION = '7.4.1';

     /**
      * SMTP line break constant.
@@ -337,8 +337,9 @@ class SMTP
                     str_replace(
                         "\n",
                         "\n                   \t                  ",
-                        trim($str)
-                    )
+                        trim($str, PHPMailer::TRIM_CHARACTERS)
+                    ),
+                    PHPMailer::TRIM_CHARACTERS
                 ),
                 "\n";
         }
@@ -424,10 +425,14 @@ class SMTP

         $errno = 0;
         $errstr = '';
+        //Warnings raised while connecting, e.g. TLS certificate verification failures,
+        //which often explain a failure better than $errstr does
+        $warnings = [];
         if ($streamok) {
             $socket_context = stream_context_create($options);
-            set_error_handler(function () {
-                call_user_func_array([$this, 'errorHandler'], func_get_args());
+            set_error_handler(function ($errno, $errmsg, $errfile = '', $errline = 0) use (&$warnings) {
+                $warnings[] = $errmsg;
+                $this->errorHandler($errno, $errmsg, $errfile, $errline);
             });
             $connection = stream_socket_client(
                 $host . ':' . $port,
@@ -443,8 +448,9 @@ class SMTP
                 'Connection: stream_socket_client not available, falling back to fsockopen',
                 self::DEBUG_CONNECTION
             );
-            set_error_handler(function () {
-                call_user_func_array([$this, 'errorHandler'], func_get_args());
+            set_error_handler(function ($errno, $errmsg, $errfile = '', $errline = 0) use (&$warnings) {
+                $warnings[] = $errmsg;
+                $this->errorHandler($errno, $errmsg, $errfile, $errline);
             });
             $connection = fsockopen(
                 $host,
@@ -458,9 +464,17 @@ class SMTP

         //Verify we connected properly
         if (!is_resource($connection)) {
+            $detail = trim(
+                (string) preg_replace(
+                    '/\s+/',
+                    ' ',
+                    implode(' ', array_unique(array_filter(array_merge($warnings, [$errstr]))))
+                ),
+                PHPMailer::TRIM_CHARACTERS
+            );
             $this->setError(
                 'Failed to connect to server',
-                '',
+                $detail,
                 (string) $errno,
                 $errstr
             );
@@ -498,6 +512,17 @@ class SMTP
             return false;
         }

+        //Anything that followed the reply to STARTTLS was sent before encryption started,
+        //so it must not be read later as if it came from the encrypted session
+        $info = stream_get_meta_data($this->smtp_conn);
+        if ($info['unread_bytes'] > 0) {
+            $this->setError('STARTTLS command failed', 'Unexpected data received before TLS negotiation');
+            $this->edebug('SMTP ERROR: ' . $this->error['error'] . ': ' . $this->error['detail'], self::DEBUG_CLIENT);
+            $this->close();
+
+            return false;
+        }
+
         //Allow the best TLS version(s) we can
         $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;

@@ -959,7 +984,7 @@ class SMTP

         foreach ($lines as $n => $s) {
             //First 4 chars contain response code followed by - or space
-            $s = trim(substr($s, 4));
+            $s = trim(substr($s, 4), PHPMailer::TRIM_CHARACTERS);
             if (empty($s)) {
                 continue;
             }
@@ -1297,9 +1322,16 @@ class SMTP
         //it can leak credentials, so hide credentials in all but lowest level
         if (
             self::DEBUG_LOWLEVEL > $this->do_debug &&
-            in_array($command, ['User & Password', 'Username', 'Password'], true)
+            in_array($command, ['User & Password', 'Username', 'Password', 'OAuth TOKEN'], true)
         ) {
             $this->edebug('CLIENT -> SERVER: [credentials hidden]', self::DEBUG_CLIENT);
+        } elseif (
+            self::DEBUG_LOWLEVEL > $this->do_debug &&
+            'AUTH' === $command &&
+            strpos($data, 'AUTH XOAUTH2 ') === 0
+        ) {
+            //The token follows the command on the same line
+            $this->edebug('CLIENT -> SERVER: AUTH XOAUTH2 [credentials hidden]', self::DEBUG_CLIENT);
         } else {
             $this->edebug('CLIENT -> SERVER: ' . $data, self::DEBUG_CLIENT);
         }
@@ -1455,7 +1487,7 @@ class SMTP

             //Deliberate noise suppression - errors are handled afterwards
             $str = @fgets($this->smtp_conn, self::MAX_REPLY_LENGTH);
-            $this->edebug('SMTP INBOUND: "' . trim($str) . '"', self::DEBUG_LOWLEVEL);
+            $this->edebug('SMTP INBOUND: "' . trim($str, PHPMailer::TRIM_CHARACTERS) . '"', self::DEBUG_LOWLEVEL);
             $data .= $str;
             //If response is only 3 chars (not valid, but RFC5321 S4.2 says it must be handled),
             //or 4th character is a space or a line break char, we are done reading, break the loop.
@@ -1646,7 +1678,7 @@ class SMTP
             foreach ($this->smtp_transaction_id_patterns as $smtp_transaction_id_pattern) {
                 $matches = [];
                 if (preg_match($smtp_transaction_id_pattern, $reply, $matches)) {
-                    $this->last_smtp_transaction_id = trim($matches[1]);
+                    $this->last_smtp_transaction_id = trim($matches[1], PHPMailer::TRIM_CHARACTERS);
                     break;
                 }
             }
diff --git a/wp-includes/version.php b/wp-includes/version.php
index c81b60859d..5dfd85d3ca 100644
--- a/wp-includes/version.php
+++ b/wp-includes/version.php
@@ -16,7 +16,7 @@
  *
  * @global string $wp_version
  */
-$wp_version = '7.3-alpha-65935';
+$wp_version = '7.3-alpha-65936';

 /**
  * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.