From 8ca031797f9d29854d11a00f2d5eef22faf77f1b Mon Sep 17 00:00:00 2001 From: LE MOINE Laurent Date: Wed, 18 Jun 2025 11:01:34 +0200 Subject: [PATCH] Added support for maximum command size during XOAUTH2 authentication --- src/SMTP.php | 33 ++++++++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/src/SMTP.php b/src/SMTP.php index 7226ee93..aebdc5e7 100644 --- a/src/SMTP.php +++ b/src/SMTP.php @@ -634,9 +634,36 @@ class SMTP } $oauth = $OAuth->getOauth64(); - //Start authentication - if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { - return false; + /* + * The maximum length for an SMTP commands is 512 bytes, according to RFC 4954 (https://datatracker.ietf.org/doc/html/rfc4954). + * (In truth this seems more complex than that, but 512 bytes seems to be the stricter limit) + * + * Therefor, the base64-encoded OAUTH token has a maximum length of 497 : 512 - 13 (AUTH XOAUTH2) - 2 (CRLF) + * If the token is longer than that, the command and the token must be sent separately + */ + if (strlen($oauth) <= 497) { + //Start authentication + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2 ' . $oauth, 235)) { + return false; + } + } else { + // Send the command and expect a code 334 + if (!$this->sendCommand('AUTH', 'AUTH XOAUTH2', 334)) { + return false; + } + + // Send the token + if (!$this->sendCommand('Oauth TOKEN', $oauth, [235, 334])) { + return false; + } + + // If the server answer with a code 334, send and empty line an wait for a code 235 + if ( + substr($this->last_reply, 0, 3) == 334 + && $this->sendCommand('AUTH End', '', 235) + ) { + return false; + } } break; default: