The classic email sending library for PHP
GNU Lesser General Public License v2.1
19317
885
9604

I followed instruction here , I have a successful result asking openssl to test the connection using CA cert. But I'm still receiving the issue.

2020-05-29 13:19:55 Connection: opening to smtp.gmail.com:587, timeout=300, options=array()
2020-05-29 13:19:55 Connection: opened
2020-05-29 13:19:55 SMTP INBOUND: "220-host.myhost.com ESMTP Exim 4.93 #2 Fri, 29 May 2020 15:19:55 +0200"
2020-05-29 13:19:55 SMTP INBOUND: "220-We do not authorize the use of this system to transport unsolicited,"
2020-05-29 13:19:55 SMTP INBOUND: "220 and/or bulk e-mail."
2020-05-29 13:19:55 SERVER -> CLIENT: 220-host.myhost.com ESMTP Exim 4.93 #2 Fri, 29 May 2020 15:19:55 +0200 220-We do not authorize the use of this system to transport unsolicited, 220 and/or bulk e-mail.
2020-05-29 13:19:55 CLIENT -> SERVER: EHLO mydomain.com
2020-05-29 13:19:55 SMTP INBOUND: "250-host.myhost.com Hello mydomain.com [162.246.248.85]"
2020-05-29 13:19:55 SMTP INBOUND: "250-SIZE 52428800"
2020-05-29 13:19:55 SMTP INBOUND: "250-8BITMIME"
2020-05-29 13:19:55 SMTP INBOUND: "250-PIPELINING"
2020-05-29 13:19:55 SMTP INBOUND: "250-AUTH PLAIN LOGIN"
2020-05-29 13:19:55 SMTP INBOUND: "250-STARTTLS"
2020-05-29 13:19:55 SMTP INBOUND: "250 HELP"
2020-05-29 13:19:55 SERVER -> CLIENT: 250-host.myhost.com Hello mydomain.com [162.246.248.85]250-SIZE 52428800250-8BITMIME250-PIPELINING250-AUTH PLAIN LOGIN250-STARTTLS250 HELP
2020-05-29 13:19:55 CLIENT -> SERVER: STARTTLS
2020-05-29 13:19:55 SMTP INBOUND: "220 TLS go ahead"
2020-05-29 13:19:55 SERVER -> CLIENT: 220 TLS go ahead
2020-05-29 13:19:55 Connection failed. Error #2: stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages:error:1416F086:SSL routines:tls_process_server_certificate:certificate verify failed [/home/xxx/vendor/phpmailer/phpmailer/src/SMTP.php line 426]
SMTP Error: Could not connect to SMTP host.
2020-05-29 13:19:55 CLIENT -> SERVER: QUIT
2020-05-29 13:19:55
2020-05-29 13:19:55
2020-05-29 13:19:55
2020-05-29 13:19:55 SMTP INBOUND: ""
2020-05-29 13:19:55
2020-05-29 13:19:55
2020-05-29 13:19:55 Connection: closed
SMTP Error: Could not connect to SMTP host.

If I use
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);

I receive
020-05-29 13:32:04 Auth method requested: UNSPECIFIED
2020-05-29 13:32:04 Auth methods available on the server: PLAIN,LOGIN
2020-05-29 13:32:04 Requested auth method not available:
2020-05-29 13:32:04 Auth method selected: LOGIN
2020-05-29 13:32:04 CLIENT -> SERVER: AUTH LOGIN
...
2020-05-29 13:32:06 SMTP INBOUND: "535 Incorrect authentication data"
2020-05-29 13:32:06 SERVER -> CLIENT: 535 Incorrect authentication data
2020-05-29 13:32:06 SMTP ERROR: Password command failed: 535 Incorrect authentication data
SMTP Error: Could not authenticate.

But I'm sure that user and password are correct!

How to sort this out?
I'm on PHP 7.3 on Centos 7

Thank you,
Luca

Discussed in #2887

Originally posted by JonthueM March 28, 2023
I notice that the address that is used for i.e. Fervent foodies is also used for The Conversation. I tried to clear it as you see below on Fervent foodies but php didn't like that lol!

foreach($_POST['growgroups'] as $growgroups)
		{
			
			if ($growgroups === 'Fervent Foodies')
			{
				$mail->Subject = "Interested in Grow Group Fervent Foodies";
				$mail->addAddress("sitemaster@1usda.org");
				$mail->send();
				$mail->addAddress("");
			} 
			if ($growgroups === 'The Conversation')
			{
				$mail->Subject = "Interested in Grow Group The Conversation";
				$mail->addAddress('michel.bkyc@gmail.com');
				$mail->send();
			}
			if ($growgroups === 'Wednesday Night Bible Study')
			{
				$mail->Subject = "Interested in Grow Group Wedensay Night Bible Study";
				$mail->addAddress('michel.bkyc@gmail.com');
				$mail->send();
			} 
			if ($growgroups === 'Its Not About Me')
			{
				$mail->Subject = "Interested in Grow Group It's Not About Me";
				$mail->addAddress('michel.bkyc@gmail.com');
				$mail->send();
			} 
			if ($growgroups === 'Young Couples Mentorship')
			{
				$mail->Subject = "Interested in Grow Group Young Couples Mentorship";
				$mail->addAddress('sitemaster@1usda.org');
				$mail->send();
			} 
			if ($growgroups === 'Whats Next')
			{
				$mail->Subject = "Interested in Grow Group Whats New";
				$mail->addAddress("michel.bkyc@gmail.com");
				$mail->send();
			}  
		}
```</div>

I just got to me that PHPMailer no longer can connect to the smtp server.

2023-03-21 14:07:28 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP Error: Could not connect to SMTP host. Failed to connect to server
Message could not be sent. Mailer Error: SMTP Error: Could not connect to SMTP host. Failed to connect to serverSMTP server error: Failed to connect to server SMTP code: 111 Additional SMTP info: Connection refused

I have websites on diffrent webhosts with diffrent mailservers and its the same problem on everyone.
No change has been made in the PHP version or on the log in information for the mail accounts.

Problem description

My comments in [].

Warning: require(/PHPMailer/src/Exception.php): Failed to open stream: No such file or directory in /Library/WebServer/Documents/sites/cognitorum/sendPHPMailer.php on line 7 — [in fact, there is one for Exeption.php]

Fatal error: Uncaught Error: Failed opening required '/PHPMailer/src/Exception.php' (include_path='.:/opt/homebrew/Cellar/php/8.2.3/share/php/pear') — [the path is correct, although in fact it starts from '/'] — in /Library/WebServer/Documents/sites/cognitorum/sendPHPMailer.php:7 Stack trace: #0 {main} thrown in /Library/WebServer/Documents/sites/cognitorum/sendPHPMailer.php on line 7

Code to reproduce

// Load PHPMailer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '/PHPMailer/src/Exception.php';
require '/PHPMailer/src/PHPMailer.php';
require '/PHPMailer/src/SMTP.php';

Debug output

my code

<?php

/**
 * This example shows settings to use when sending via Google's Gmail servers.
 * This uses traditional id & password authentication - look at the gmail_xoauth.phps
 * example to see how to use XOAUTH2.
 * The IMAP section shows how to save this message to the 'Sent Mail' folder using IMAP commands.
 */

//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;

require 'C:\Users\*******\vendor\autoload.php';

//Create a new PHPMailer instance
$mail = new PHPMailer();

//Tell PHPMailer to use SMTP
$mail->isSMTP();

//Enable SMTP debugging
//SMTP::DEBUG_OFF = off (for production use)
//SMTP::DEBUG_CLIENT = client messages
//SMTP::DEBUG_SERVER = client and server messages
$mail->SMTPDebug = SMTP::DEBUG_SERVER;

//Set the hostname of the mail server
$mail->Host = 'smtp.gmail.com';
//Use `$mail->Host = gethostbyname('smtp.gmail.com');`
//if your network does not support SMTP over IPv6,
//though this may cause issues with TLS

//Set the SMTP port number:
// - 465 for SMTP with implicit TLS, a.k.a. RFC8314 SMTPS or
// - 587 for SMTP+STARTTLS
$mail->Port = 587;

//Set the encryption mechanism to use:
// - SMTPS (implicit TLS on port 465) or
// - STARTTLS (explicit TLS on port 587)
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;

//Whether to use SMTP authentication
$mail->SMTPAuth = true;

//Username to use for SMTP authentication - use full email address for gmail
$mail->Username = ********@gmail.com';

//Password to use for SMTP authentication
$mail->Password = '********';

//Set who the message is to be sent from
//Note that with gmail you can only use your account address (same as `Username`)
//or predefined aliases that you have configured within your account.
//Do not use user-submitted addresses in here
$mail->setFrom('*********', 'First Last');

//Set an alternative reply-to address
//This is a good place to put user-submitted addresses
$mail->addReplyTo('replyto@example.com', 'First Last');

//Set who the message is to be sent to
$mail->addAddress('whoto@example.com', 'John Doe');

//Set the subject line
$mail->Subject = 'PHPMailer GMail SMTP test';

//Read an HTML message body from an external file, convert referenced images to embedded,
//convert HTML into a basic plain-text alternative body
$mail->msgHTML(file_get_contents('contents.html'), __DIR__);

//Replace the plain text body with one created manually
$mail->AltBody = 'This is a plain-text message body';

//Attach an image file
$mail->addAttachment('images/phpmailer_mini.png');

//send the message, check for errors
if (!$mail->send()) {
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message sent!';
    //Section 2: IMAP
    //Uncomment these to save your message in the 'Sent Mail' folder.
    #if (save_mail($mail)) {
    #    echo "Message saved!";
    #}
}

//Section 2: IMAP
//IMAP commands requires the PHP IMAP Extension, found at: https://php.net/manual/en/imap.setup.php
//Function to call which uses the PHP imap_*() functions to save messages: https://php.net/manual/en/book.imap.php
//You can use imap_getmailboxes($imapStream, '/imap/ssl', '*' ) to get a list of available folders or labels, this can
//be useful if you are trying to get this working on a non-Gmail IMAP server.
function save_mail($mail)
{
    //You can change 'Sent Mail' to any other folder or tag
    $path = '{imap.gmail.com:993/imap/ssl}[Gmail]/Sent Mail';

    //Tell your server to open an IMAP connection using the same username and password as you used for SMTP
    $imapStream = imap_open($path, $mail->Username, $mail->Password);

    $result = imap_append($imapStream, $path, $mail->getSentMIMEMessage());
    imap_close($imapStream);

    return $result;
}

I have a problem. I added the following lines to the config.php and config_extend file:

define('PHPMAILERHOST','smtp.nameserver.com:587');
define('PHPMAILER_SMTPUSER','');
define('PHPMAILER_SMTPPASS','');
define('PHPMAILERPORT', 587);
define('PHPMAILER_SECURE', 'tls');
define('POP_BEFORE_SMTP', false);

**define('PHPMAILERTESTHOST','testsmtp.nameserver.com');
define('PHPMAILERBLASTHOST','nameserver.com');
define('PHPMAILERBLASTPORT',25);

define('SMTP_TIMEOUT',5);
define('POPBEFORESMTP_DEBUG',false);**

But I still see SMTP errors in the event log. Can you please help me troubleshoot this issue?
SMTP connect() failed when sending to [Please refer to https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting for assistance.

PHPMailer function mailPassthru adds a fifth parameter to mail instead of proper detection (and use four parameters if PHP is in safe mode). This results in a kindof misleading error "Could not instantiate mail function" and the troubleshooting guide wrongly pointing in the direction to search for server issues.
Please either fix the detection, show a proper message and / or adjust the troubleshooting guide.
Took me an hour!
Thank you.

Hi, first of all thank you for your work.

It's been a few months now that I haven't been able to solve my problem even with the most recent PHPMailer. Sending an email without an attachment is always correctly done but I've never been able to have a valid signature when adding a PDF as attachment. I even tried the

instead of calling normalizeBreaks() i call SimpleBodyCanonicalization() at DKIM_BodyC

mentionned by gothge on 30/11/2017

Also I have seen there was an issue before with attachments that seemed to even having been tested but no luck on my side. Maybe I'm missing something? Even though I did read the recently added example.
By just removing the 2 lines that adds my attachment I get a correctly signed DKIM email.

<?php
require_once "vendor/PHPMailer/phpmailer/src/PHPMailer.php";
require_once "vendor/PHPMailer/phpmailer/src/Exception.php";
use PHPMailer\PHPMailer\PHPMailer;

function sendEmail($subject,$content,$email,$altBody,$orderRef4pdf=""){

    $emailObject = new PHPMailer();
    $emailObject->From      = 'info@website.com';
    $emailObject->FromName  = 'My Website';
    $emailObject->Subject   = $subject;
    //$email->Body      = $content;
    $emailObject->MsgHTML($content);
    $emailObject->IsHTML(true);
    $emailObject->CharSet="utf-8";

    //Replace the plain text body with one created manually
    $emailObject->AltBody = $altBody;
    $emailObject->addReplyTo('info@website.com', 'My Website');
    $emailObject->AddAddress($email);
    $emailObject->DKIM_domain='website.com';
    $emailObject->DKIM_private="dkim_private.pem";
    $emailObject->DKIM_selector = '000000000.website';
    $emailObject->DKIM_identity=$emailObject->From;
    $emailObject->DKIM_copyHeaderFields=false;


    //Add attachment
    $file_to_attach = 'invoices/invoice_'.$orderRef4pdf.'.pdf';
    $emailObject->AddAttachment( $file_to_attach , 'invoice_'.$orderRef4pdf.'.pdf' );

    return $emailObject->Send();
}

Hi,

I installed and configured PHPMailer with my gmail account and it sends the emails. But the issue its displaying long progress message apart from the "Successfully sent message".

I need to skip this progress reporting messages and just display whether the email has successfully send or not.

these are the waste messages:

SERVER -> CLIENT: 220 mx.google.com ESMTP ei3sm22221361pbc.91 - gsmtp
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-mx.google.com at your service, [203.94.68.194]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
CLIENT -> SERVER: STARTTLS
SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
CLIENT -> SERVER: EHLO localhost
SERVER -> CLIENT: 250-mx.google.com at your service, [203.94.68.194]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH XOAUTH2 PLAIN-CLIENTTOKEN250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
CLIENT -> SERVER: AUTH LOGIN
SERVER -> CLIENT: 334 VXNlcm5hbWU6
CLIENT -> SERVER: dW1wd2Vic29sdXRpb25zQGdtYWlsLmNvbQ==
SERVER -> CLIENT: 334 UGFzc3dvcmQ6
CLIENT -> SERVER: bWFkdXNoYW44Ng==
SERVER -> CLIENT: 235 2.7.0 Accepted
CLIENT -> SERVER: MAIL FROM:email@sender.lk
SERVER -> CLIENT: 250 2.1.0 OK ei3sm22221361pbc.91 - gsmtp
CLIENT -> SERVER: RCPT TO:udara86@gmail.com
SERVER -> CLIENT: 250 2.1.5 OK ei3sm22221361pbc.91 - gsmtp
CLIENT -> SERVER: DATA
SERVER -> CLIENT: 354 Go ahead ei3sm22221361pbc.91 - gsmtp
CLIENT -> SERVER: Date: Thu, 19 Feb 2015 09:15:19 +0000
CLIENT -> SERVER: To: 11 SLSC udara86@gmail.com
CLIENT -> SERVER: From: SENDER s NAME email@sender.lk
CLIENT -> SERVER: Reply-To: Reply To Me udara@army.lk
CLIENT -> SERVER: Subject: Testing Emil Header :
CLIENT -> SERVER: Message-ID: f5de5be1309570ebfc316007a92bc5f2@localhost
CLIENT -> SERVER: X-Priority: 3
CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.9 (https://github.com/PHPMailer/PHPMailer/)
CLIENT -> SERVER: MIME-Version: 1.0
CLIENT -> SERVER: Content-Type: multipart/mixed;
CLIENT -> SERVER: boundary="b1_f5de5be1309570ebfc316007a92bc5f2"
CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_f5de5be1309570ebfc316007a92bc5f2
CLIENT -> SERVER: Content-Type: multipart/alternative;
CLIENT -> SERVER: boundary="b2_f5de5be1309570ebfc316007a92bc5f2"
CLIENT -> SERVER:
CLIENT -> SERVER: --b2_f5de5be1309570ebfc316007a92bc5f2
CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
CLIENT -> SERVER:
CLIENT -> SERVER: This is a test of PHPMailer.
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: This example uses HTML.
CLIENT -> SERVER: The PHPMailer image at the top has been embedded automatically.
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: --b2_f5de5be1309570ebfc316007a92bc5f2
CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: <title>PHPMailer Test</title>
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:


CLIENT -> SERVER:

This is a test of PHPMailer.


CLIENT -> SERVER:

CLIENT -> SERVER:
CLIENT -> SERVER: PHPMailer rocks
CLIENT -> SERVER:
CLIENT -> SERVER:

CLIENT -> SERVER:

This example uses HTML.


CLIENT -> SERVER:

The PHPMailer image at the top has been embedded automatically.


CLIENT -> SERVER:

CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: --b2_f5de5be1309570ebfc316007a92bc5f2--
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_f5de5be1309570ebfc316007a92bc5f2
CLIENT -> SERVER: Content-Type: image/png; name="phpmailer_mini.png"
CLIENT -> SERVER: Content-Transfer-Encoding: base64
CLIENT -> SERVER: Content-Disposition: attachment; filename=phpmailer_mini.png
CLIENT -> SERVER:
CLIENT -> SERVER: iVBORw0KGgoAAAANSUhEUgAAAEgAAABICAIAAADajyQQAAAAA3NCSVQICAjb4U/gAAAACXBIWXMA
CLIENT -> SERVER: AAs6AAALOgFkf1cNAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAABrBJREFU
CLIENT -> SERVER: eNrtm4lPFFccx/s/AXuwLCvrcsNyyw1luc9KrUUgFgzh9ACqFmIKQsBQEAUFagAROZagHFbkbFUK
CLIENT -> SERVER: SEAJLYJgSQD7jS/S6czswbITtX3fvJDZt+/3e/uZd868H19Y/EdFwSgYBaNg5gI7f/78Rd0qLS09
CLIENT -> SERVER: c+ZMcnJyUFCQg4ODlZWVMdX4uMlLMj0ESieiHYwC29jYeGe0Xr58WV5eDkL9YJaWFtUFvtsjKWZP
CLIENT -> SERVER: 482RKjuJ+cGINjc38/PzLfHz9eridx7mpXpY/6XCRgTPQoERPXjwwNbWVj9b3jdufw2bh6qnOlQm
CLIENT -> SERVER: JQNBYDBofHzczs5OP1tmotPWUPIhqdrKA8Ui0kGEByPq7u62MKSvNPYbg0kmU9UXH7OyIlSHAyss
CLIENT -> SERVER: LDzBUFZW1uXLl+/du7e7u8vLlpqaapAtOkj5pzbRBKrKPB/iwQxgPj78vlxcXO7evcsFm52dNabu
CLIENT -> SERVER: EB/FSl/CgaiKM9UwFBwMwjrW3t7OZQsJCWFN97zydZcvdsUZg/R2KDkn1UXHWiIAGCQSiWZmZlgm
CLIENT -> SERVER: tbW1zDLfn/b0crHhNXdztJ5tj9FPtfkwOS3OiddcKrZsKDkmCBhUV1fHMhkZGWEWqC/2X74fH+Sl
CLIENT -> SERVER: 4DV3UEqnWqJ0Ua0PJiWGH+U1lFuLBuvC4VkoMEwnLJO5uTkWGH7iH9rEyAD+xcBOLh5tjOBSrfYn
CLIENT -> SERVER: avz5TZS24l9uaFBGQLDAwEDuXoQLRm5/UriK//bLRNraMCbVcnd8oCf/iu94VDpNGllQsJiYGJbJ
CLIENT -> SERVER: q1evuGCGB4zEqrMimBSb74z1dJHxFlM7yX5vj0UZwcGKiopYJv39/SwwzhTnyusKC2/zpYDffo52
CLIENT -> SERVER: VlnzFjimli91xxM/goM9evSIZVJRUcEFY6ULGWpd07eurW2435GVXrL0CQ926tSpdxydPHnSIBjS
CLIENT -> SERVER: j7neFkYrNkS5NkA2K8KDYXStrq6yyr9+/VqpVBoDhvTTBcMbP+jrKAeyvRQczN3dvbKykne7iGcz
CLIENT -> SERVER: FDASDKm1LEj/Vv10kvNb8rBjXjA8aN1nCIuvnieAyclJ7LMOBIbUXRVqLYEVjwq/dSePcOYAM1Vo
CLIENT -> SERVER: wLCwMDg5KBgS9hC2Mvac8UO2lyFD4cFARTqhaWBIY02aowrJ/txYU+SLzI8Mtr29nZmZCfPDgCH9
CLIENT -> SERVER: 2hbtpJJiNmm6FICPHxkMT2Vubm6wPTwY0lxHLIYcLj4C2NbW1sLCglarPXfunIeHBzE8HBg3CQ8W
CLIENT -> SERVER: Ghp6hCEbG/aT1ecKxl3HKBgFo2AUjIJRMApGwSgYBaNgnwMYXt08+bfIQ+RhhHejOHMQKN2vDqUh
CLIENT -> SERVER: RxSMglEwCkbBPqimpubGe12/fh0ROH5+fiT/ypUrnp6ezJLFxcUkngOnYcQEqqqq2j8cQ1gjcjIy
CLIENT -> SERVER: MphWYrG4oaEB+VKpVNeJdn19PS5ycnLa2trMBobTLfBkZ2fDb2dnJ47JIyMjkY9AgKioKGbJ0dHR
CLIENT -> SERVER: tLQ0XCCqAy9PYQIBDEGMjY2NyIef5eXl+fl5phVokYkNjVwut+AT3sDi7BcXubm5iI4xJxhpJaLb
CLIENT -> SERVER: t293dXUZBKuurv4nTio6em9vDyF+ALt169bi4iLCUZkOy8rKWGDcWEdeMBQzGxgaYWJi4kBg6Gw7
CLIENT -> SERVER: OztwQsCuXr2KI0LylUQigX8vLy8CBsHJ0tLSmzdvHj9+nJCQgDIRERG9vb1MMDi8du0ajk7X1tZw
CLIENT -> SERVER: l1UqFTJbW1vT09Pz8vJgaAoYPPb19REwRAMHMjQ1NcULRsI+cFpLwPARL/rJV8ePHweJTCYjYGgB
CLIENT -> SERVER: vDPHQSGJgiHxPHFxcfDMBCsoKMAOFjFp8NnR0XHz5k1kDgwMIOgCgbv+/v7GgqHnYGSjYpwMrays
CLIENT -> SERVER: oEoC9uzZsycMYfjtg4EfJhBe9ON+Dw8PI5+A4eL58+fBwcG4wGSAXwkwbldEM+KEjRdsaGgIHYeU
CLIENT -> SERVER: TElJwaAlYGixg3VF/GI8vOBienr67NmzqNVgV8T5GEygFy9etLS0IPyZCYb7ig4JbPi0t7dntlhJ
CLIENT -> SERVER: SQm6OsLM0FzI5AVD1WNjY9r3QrH19XWTwEhX5Mj4MUbEBENroDciiHNwcBAf98Ew36IXkGhbhUKh
CLIENT -> SERVER: CwzYaDH3D3J2dv5UwCA0/tOnTzFKmWBYUXp6epCzD4Y25ILhL8v/JwSGLo31DVMFEwzdEv2qubn5
CLIENT -> SERVER: zp076GyouqmpiQuGcYti6LFYuDFz4F8eTAHTaDSomJuPcADcVNYWATMvWVLVajXXxNXV1dvbmzcu
CLIENT -> SERVER: FZEvZDLEcoedSkBAAD5iMUAtgCcbGkdHx/1bjFuAYpjM4uPjSV0wQe10r0jBKBgFo2D/a7C/Af4W
CLIENT -> SERVER: rkfDK5+FAAAAAElFTkSuQmCC
CLIENT -> SERVER:
CLIENT -> SERVER:
CLIENT -> SERVER: --b1_f5de5be1309570ebfc316007a92bc5f2--
CLIENT -> SERVER:
CLIENT -> SERVER: .
SERVER -> CLIENT: 250 2.0.0 OK 1424337324 ei3sm22221361pbc.91 - gsmtp
CLIENT -> SERVER: QUIT
SERVER -> CLIENT: 221 2.0.0 closing connection ei3sm22221361pbc.91 - gsmtp
Message sent!

We recently updated PHPMailer from an ancient 5.2 version to the latest, 6.7.1.

We have a bit of an exotic setup, with PHPMailer using the mail driver, then nullmailer handles sending the email to a remote SMTP server. This is done for performance purposes, so we don't have to wait synchronously for PHPMailer to connect to the SMTP server and block the user while it is doing it.

When sending multi multipart/mixed emails, the raw email looks as follows:

...
X-Mailer: PHPMailer 6.7.1 (https://github.com/PHPMailer/PHPMailer)
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="b1=_123"
Content-Transfer-Encoding: 8bit

--b1=_123

Content-Type: text/html; charset=UTF-8

Content-Transfer-Encoding: 8bit

Notice the extra new lines after the boundary between the two Content entries. It should be:

X-Mailer: PHPMailer 6.7.1 (https://github.com/PHPMailer/PHPMailer)
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="b1=_123"
Content-Transfer-Encoding: 8bit

--b1=_123
Content-Type: text/html; charset=UTF-8
Content-Transfer-Encoding: 8bit

We narrowed it down to this block in preSend:

    public function preSend()
    {
        if (
            'smtp' === $this->Mailer
            || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
        ) {
            //SMTP mandates RFC-compliant line endings
            //and it's also used with mail() on Windows
            static::setLE(self::CRLF);
        } else {
            //Maintain backward compatibility with legacy Linux command line mailers
            static::setLE(PHP_EOL);
        }

Because we are running the mailer driver and PHP 8.1, static::setLE(self::CRLF); is triggered. But since we are using a legacy Linux CLI mailer, what we need is static::setLE(PHP_EOL);.

Now, I understand our setup is not ideal, convoluted and probably not common.

However, I would have appreciated more flexibility for setting the line endings. I had to overwrite setLE in a child class to prevent the CRLF call from modifying the line endings.

Maybe this block could be extracted to a smaller, overwritable function? Or this could be an editable parameter somewhere? I had something like this in mind:

    public function setLineEndings()
    {
        if (
            'smtp' === $this->Mailer
            || ('mail' === $this->Mailer && (\PHP_VERSION_ID >= 80000 || stripos(PHP_OS, 'WIN') === 0))
        ) {
            //SMTP mandates RFC-compliant line endings
            //and it's also used with mail() on Windows
            static::setLE(self::CRLF);
        } else {
            //Maintain backward compatibility with legacy Linux command line mailers
            static::setLE(PHP_EOL);
        }
    }

    public function preSend()
    {
        $this->setLineEndings();
...
require_once('PHPMailer/src/PHPMailer.php');
require_once('PHPMailer/src/SMTP.php');
require_once('PHPMailer/src/Exception.php');

        $subject = "Password Resert";
        $body = "Hi ";
        $sender_email = $_POST['email'];
        $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
        try {
            //Server settings
            $mail->SMTPDebug = 0;                              // Enable verbose debug output
            $mail->isSMTP();                                   // Send using SMTP
            $mail->Host       = 'smtp.gmail.com';              // Set the SMTP server to send through
            $mail->SMTPAuth   = true;                          // Enable SMTP authentication
            $mail->Username   = 'username@gmail.com';    // SMTP username
            $mail->Password   = 'password';            // SMTP password
            $mail->SMTPSecure = "ssl";                         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port       = 465;                           // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above
            //Recipients
             $mail->setFrom('username@gmail.com', 'project');
            $mail->addAddress('test@mailinator.com');                  // Name is optional

            // Content
            $mail->isHTML(true);                               // Set email format to HTML
            $mail->Subject = $subject;
            $mail->Body    = $body;
            $mail->send();

        } catch (Exception $e) {
            print_r($e);
            exit;
        }

Hi,
i have a problem with sending HTML and UTF-8 encoded E-mails with PHP-Mailer Version 6.0.3 and i hope one can help me here. I could not find anything about this issue on the web and also not here in the docs. It seems that the order of how i Enter a message into the AltBody and Body Properties makes a difference but i could not figure out why and how...
Let me know if some else information is needed
Thanks in advance
M.

Problem description

I try sending an E-Mail with CharSet UTF-8 but i get only the Alt-Body encoded with UTF-8 the normal HTML-body ($mail->Body='test') comes encoded as ascii.

Code to reproduce

date_default_timezone_set('Europe/Vienna');
$mail = new PHPMailer(true);   
$mail->setLanguage("de");  
// Server-Settings
$mail->IsSMTP();    
$mail->Host     = $SMTPServer;
$mail->SMTPAuth = true;
$mail->Username = $SMTPUsername;
$mail->Password = $SMTPPassword;
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$mail->From     = $emailAbsenderEmail;      
$mail->FromName = $emailAbsenderName;
$mail->AddAddress($emailEmpfaenger); 
$mail->AddCC($emailCC);
$mail->AddBCC($emailBCC);
$mail->AddAttachment($datei);
$mail->AddAttachment($dateiAGB);

$mail->IsHTML(true); 
$mail->Subject = $emailBetreff; 
$mail->AltBody = "HTML Emails not supported by your Client.";
$mail->Body = 'Test mit ÜmlÄuten Äber pässt;';
$mail->CharSet = 'UTF-8';     
$mail->Send();

Debug output

This is a part of the E-Mails Source-Code (out of Thunderbird), and here you can see, the text/html part is not encoded with charset=UTF-8, but why?

Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

HTML Emails not supported by your Client.

Content-Type: text/html; charset=us-ascii

Test mit ÜmlÄuten Äber pässt;

BACKGROUND
I am running PHP 5.6 and Steven Maguire’s Microsoft Provider extension to thephpleague’s oauth2-client in order to use the MSFT Identity Platform V2.0 authorization and token endpoints and the MSFT Graph V1.0 API with PHPMailer.
The V2 end-points and Graph are needed to support SMTP AUTH with Oauth2 (as announced in May 2020), and my MSFT tenant has SMTP AUTH enabled (MSFT is disabling it by default for new tenants).

I have made the obvious changes (below) needed to Steven’s code to support v2.0 endpoints and the Graph API v1.0.

PROBLEM DESCRIPTION
Running my get_oauth_token manually successfully gives a refresh token that is pasted into my PHPMailer invocation code.
But subsequently invoking PHPMailer results in a 535 5.7.3 authentication failure:
(A 535 5.7.3 fail code is not in RFC 4954’s code list but seems a common enough ‘invalid credentials’ error.)
I have posted variants of this problem on thephpleague/oauth2-client and stevenmaguire/oauth2-client repositories and also on the thenetworg/oauth2-azure (which has its own provider code)

DEBUG OUPUT
SMTP ERROR: AUTH command failed: 535 5.7.3 Authentication unsuccessful [AM3PR05CA0135.eurprd05.prod.outlook.com]

However: running get_oauth_token manually is recorded in AAD Sign-ins but subsequently invoking PHPMailer is not. It appears that whatever calls get_oauth_token (whether directly or by callback from an endpoint) is not doing so and hence not obtaining authentication.

I am baffled and clearly doing something daft. Any suggestions are most welcome, especially from anyone who has successfully implemented this using v2.0 endpoints and the Graph API.

CODE DETAIL

My compose.json ‘requires’ just:

 "phpmailer/phpmailer": "dev-master"     …… which should pick up PHPMailer 6.1
 "stevenmaguire/oauth2-microsoft": "dev-master"

My changes to the Steven Maguire’s Provider code are in vendor/stevenmaguire/oauth2-microsoft/src/Provider/Microsoft.php:

    public $defaultScopes = ['Mail.Send SMTP.Send offline_access openid profile email User.Read']
    protected $urlAuthorize = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/authorize'
    protected $urlAccessToken = 'https://login.microsoftonline.com/organizations/oauth2/v2.0/token'
    protected $urlResourceOwnerDetails = 'https://graph.microsoft.com/v1.0/me'

My PHPMailer invocation is:

session_start();
require 'vendor/autoload.php';
require_once('vendor/phpmailer/phpmailer/src/OAuth.php');
require_once('vendor/phpmailer/phpmailer/src/PHPMailer.php');
require_once('vendor/phpmailer/phpmailer/src/SMTP.php');
require_once('vendor/phpmailer/phpmailer/src/Exception.php');
require_once('vendor/stevenmaguire/oauth2-microsoft/src/Provider/Microsoft.php');

use phpmailer\phpmailer\OAuth;
use phpmailer\phpmailer\PHPMailer;
use phpmailer\phpmailer\SMTP;
use phpmailer\phpmailer\Exception;
use Stevenmaguire\OAuth2\Client\Provider\Microsoft; 

$mail = new PHPMailer;
$mail->isSMTP();                                      
$mail->Host = 'smtp.office365.com';
$mail->SMTPAuth = true;                  // Enable SMTP authentication
$mail->AuthType = 'XOAUTH2';             // Select OAUTH2 
$mail->SMTPDebug = SMTP::DEBUG_LOWLEVEL;
$mail->SMTPSecure = 'tls';               // Enable TLS encryption
$mail->Port = 587;
//$mail->Username = [my email address];    //only for Basic Authentication AuthType
//$mail->Password = [my email password];  //only for Basic Authentication AuthType

$username = ‘[my email address]’;    
$clientId = '[my client ID from AAD]';
$clientSecret = '[my client secret from AAD]';
$redirectURI = '[URI of my get_oauth_token.php module, as registered with AAD';
$refreshToken = '[1049 character token, extracted from get_oauth_token’s response] ';
$mail -> refresh_token = $refreshToken;

$provider = new Microsoft([
    'clientId'          => $clientId,
    'clientSecret'      => $clientSecret,
    'redirectUri'       => $redirectURI
]);

$provider->urlAPI = ‘https://graph.microsoft.com/v1.0/’;
$provider->scope = ‘openid  SMTP.Send Mail.Send offline_access profile email User.Read’;

$mail->setOAuth(
        new OAuth(
            [
                'provider' => $provider,
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
               ‘refreshToken' => $refreshToken, 
                'userName' =>$username
            ]
        )
   );
// The remaining code is purely PHPMailer and works fine with Basic Authentication

My GET_AUTH_TOKEN.PHP is:
… just a Microsoft-specific and slightly pruned version of Steven’s own. The ‘Select Provider’ is thus strictly unnecessary.

<?php
namespace PHPMailer\PHPMailer;
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;

if (!isset($_GET['code']) && !isset($_GET['provider'])) {
?>
<html>
<body>Select Provider:<br/>
<a href='?provider=Microsoft'>Microsoft/Outlook/Hotmail/Live/Office365</a><br/>
</body>
</html>
<?php

exit;
}
require 'vendor/autoload.php';

session_start();

$providerName = '';

if (array_key_exists('provider', $_GET)) {
    $providerName = $_GET['provider'];
    $_SESSION['provider'] = $providerName;
} elseif (array_key_exists('provider', $_SESSION)) {
    $providerName = $_SESSION['provider'];
}

$clientId = [my client ID from AAD];
$clientSecret = [my client secret from AAD]';
$redirectUri = [URI of this module, as registered with AAD ';

$params = [
    'clientId' => $clientId,
    'clientSecret' => $clientSecret,
    'redirectUri' => $redirectUri,
    'accessType' => 'offline'
];

$options = [];
$provider = null;

switch ($providerName) {
        case 'Microsoft':
        $provider = new Microsoft($params);
        break;
}

$provider->scope = ‘openid  SMTP.Send Mail.Send offline_access profile email User.Read’;

if (!isset($_GET['code'])) {
    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl($options);
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;

// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    unset($_SESSION['provider']);
    exit('Invalid state');
} else {
    unset($_SESSION['provider']);
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken(
        'authorization_code',
        [
            'code' => $_GET['code']
        ]
    );
    
    echo 'Refresh Token: ', $token->getRefreshToken();
}

hi everyone,
good news and bad news. last week finally i got the refresh token from google and phpmailer started working perfectly.
today for apparently no reason, it stopped. no mail can be sent.
that's the error reported in apache log:

PHP Fatal error:  Uncaught League\\OAuth2\\Client\\Provider\\Exception\\IdentityProviderException: invalid_grant in /var/www/html/mailer/vendor/league/oauth2-google/src/Provider/Google.php:118
Stack trace:
#0 /var/www/html/mailer/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(628): League\\OAuth2\\Client\\Provider\\Google->checkResponse()
#1 /var/www/html/mailer/vendor/league/oauth2-client/src/Provider/AbstractProvider.php(537): League\\OAuth2\\Client\\Provider\\AbstractProvider->getParsedResponse()
#2 /var/www/html/mailer/vendor/phpmailer/phpmailer/src/OAuth.php(115): League\\OAuth2\\Client\\Provider\\AbstractProvider->getAccessToken()
#3 /var/www/html/mailer/vendor/phpmailer/phpmailer/src/OAuth.php(128): PHPMailer\\PHPMailer\\OAuth->getToken()
#4 /var/www/html/mailer/vendor/phpmailer/phpmailer/src/SMTP.php(598): PHPMailer\\PHPMailer\\OAuth->getOauth64()
#5 /var/www/html/mailer/vendor/phpmailer/phpmailer/src/PHPMailer.php(2209): PHPMailer\\PHPMailer\\SMTP->authenticate()
#6 /var/www/html/mailer/vendor/phpmailer/phpmailer/src/PHPMaile in /var/www/html/mailer/vendor/league/oauth2-google/src/Provider/Google.php on line 118

and that's the debug:

2023-01-22 20:38:01 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP v10-20020a170906292a00b00782fbb7f5f7sm21215734ejd.113 - gsmtp
2023-01-22 20:38:01 CLIENT -> SERVER: EHLO 192.168.1.29
2023-01-22 20:38:01 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [x.x.x.x.x]250-SIZE 35882577250-8BITMIME250-STARTTLS250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2023-01-22 20:38:01 CLIENT -> SERVER: STARTTLS
2023-01-22 20:38:01 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2023-01-22 20:38:01 CLIENT -> SERVER: EHLO 192.168.1.29
2023-01-22 20:38:01 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [x.x.x.x]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2023-01-22 20:38:01 CLIENT -> SERVER: QUIT
2023-01-22 20:38:01 SERVER -> CLIENT: 221 2.0.0 closing connection v10-20020a170906292a00b00782fbb7f5f7sm21215734ejd.113 - gsmtp

i changed nothing about the core script that worked until today, i cannot see the reason of the crash.
can anybody please help me?

Problem description

Glpi 10.0.0.5 hosted on a Ubuntu 22.04 serveur, with apache2/mariaDB

When configuring the Notification to mail / smtp, test mail to the admin imemdiately get an error notification.
tried again with debug mode, log from files/_log/mail-debug.log

2023-01-24 15:30:23 [500@s-web]
3 - Connection: opening to smtp.viry.net:8082, timeout=300, options=array()2023-01-24 15:30:23 [500@s-web]
3 - Connection: opened2023-01-24 15:30:23 [500@s-web]
2 - SERVER -> CLIENT: 2023-01-24 15:30:23 [500@s-web]
3 - Connection: closing due to error2023-01-24 15:30:23 [500@s-web]
3 - Connection: closed2023-01-24 15:30:23 [500@s-web]
3 - SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting2023-01-24 15:32:40 [500@s-web]

smtp.viry.net:8082 is a relay smtp server on windows server, and my ubuntu server (s-web.viry.net) au authorized to connect to the relay.

we have on old version en glpi (0.85) with the same notification smtp parameter working fine.
i'd like the new version work too.

SMTP.php currently has the following code:

        //Allow the best TLS version(s) we can
        $crypto_method = STREAM_CRYPTO_METHOD_TLS_CLIENT;

        //PHP 5.6.7 dropped inclusion of TLS 1.1 and 1.2 in STREAM_CRYPTO_METHOD_TLS_CLIENT
        //so add them back in manually if we can
        if (defined('STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT')) {
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
            $crypto_method |= STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
        }

For security reasons, I need to be able to disable TLS 1.0 and 1.1 and enable TLS 1.3. Unfortunately, PHPMailer is hardcoded to accept TLS 1.0 through 1.2 and reject TLS 1.3.

I'm trying to use PHPMailer with Google's oAuth but I get Username and Password not accepted error while trying to send an email.


Error:

2022-06-08 14:13:22 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP ay13-20020a05600c1e0d00b003974b95d897sm18665416wmb.37 - gsmtp
2022-06-08 14:13:22 CLIENT -> SERVER: EHLO XXX
2022-06-08 14:13:22 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [78.142.4.100]250-SIZE 35882577250-8BITMIME250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH250-ENHANCEDSTATUSCODES250-PIPELINING250-CHUNKING250 SMTPUTF8
2022-06-08 14:13:22 CLIENT -> SERVER: AUTH XOAUTH2 XXX
2022-06-08 14:13:23 SERVER -> CLIENT: 334 XXX
2022-06-08 14:13:23 SMTP ERROR: AUTH command failed: 334 XXX
SMTP Error: Could not authenticate.
2022-06-08 14:13:23 CLIENT -> SERVER: QUIT
2022-06-08 14:13:23 SERVER -> CLIENT: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/?p=BadCredentials ay13-20020a05600c1e0d00b003974b95d897sm18665416wmb.37 - gsmtp
2022-06-08 14:13:23 SMTP ERROR: QUIT command failed: 535-5.7.8 Username and Password not accepted. Learn more at535 5.7.8 https://support.google.com/mail/?p=BadCredentials ay13-20020a05600c1e0d00b003974b95d897sm18665416wmb.37 - gsmtp
SMTP Error: Could not authenticate.

Code:

<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\OAuth;
use PHPMailer\PHPMailer\Exception;
use League\OAuth2\Client\Provider\Google;

function sendMail($recipient, $subject, $content) {
    $mail = new PHPMailer(true);

    try {
        $email = 'XXX';
        $clientId = 'XXX';
        $clientSecret = 'XXX';
        $refreshToken = 'XXX';

        $provider = new Google(
            [
                'clientId' => $clientId,
                'clientSecret' => $clientSecret,
            ]
        );

        $mail->isSMTP();
        $mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->Host = 'smtp.gmail.com';
        $mail->Port = 465;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        $mail->SMTPAuth = true;
        $mail->AuthType = 'XOAUTH2';
        $mail->setOAuth(
            new OAuth(
                [
                    'provider' => $provider,
                    'clientId' => $clientId,
                    'clientSecret' => $clientSecret,
                    'refreshToken' => $refreshToken,
                    'userName' => $email,
                ]
            )
        );

        $mail->setFrom('XXX', 'XXX');
        $mail->addAddress($recipient);
        $mail->isHTML(true);
        $mail->Subject = $subject . ' | XXX';
        $mail->Body = $content;
        $mail->CharSet = PHPMailer::CHARSET_UTF8;
        $mail->send();

        return TRUE;
    }
    catch(Exception $e) {
        return FALSE;
    }
}
?>

hi everyone,
i'm trying to have access to gmail using oauth2 from localhost. i've done everything as the tutorail says (https://github.com/PHPMailer/PHPMailer/wiki/Using-Gmail-with-XOAUTH2), but i cannot have a token from google. in particular i run get_access_token.php, select google, consent, but i obtain only a blank screen with no code.
i've no idea where the issue is, can someone help me please?

that's the code i run

<?php
/**
 * PHPMailer - PHP email creation and transport class.
 * PHP Version 5.5
 * @package PHPMailer
 * @see https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
 * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
 * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
 * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
 * @author Brent R. Matzelle (original founder)
 * @copyright 2012 - 2017 Marcus Bointon
 * @copyright 2010 - 2012 Jim Jagielski
 * @copyright 2004 - 2009 Andy Prevost
 * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
 * @note This program is distributed in the hope that it will be useful - WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.
 */
/**
 * Get an OAuth2 token from an OAuth2 provider.
 * * Install this script on your server so that it's accessible
 * as [https/http]://<yourdomain>/<folder>/get_oauth_token.php
 * e.g.: http://localhost/phpmailer/get_oauth_token.php
 * * Ensure dependencies are installed with 'composer install'
 * * Set up an app in your Google/Yahoo/Microsoft account
 * * Set the script address as the app's redirect URL
 * If no refresh token is obtained when running this file,
 * revoke access to your app and run the script again.
 */

namespace PHPMailer\PHPMailer;

/**
 * Aliases for League Provider Classes
 * Make sure you have added these to your composer.json and run `composer install`
 * Plenty to choose from here:
 * @see http://oauth2-client.thephpleague.com/providers/thirdparty/
 */
// @see https://github.com/thephpleague/oauth2-google
use League\OAuth2\Client\Provider\Google;
// @see https://packagist.org/packages/hayageek/oauth2-yahoo
use Hayageek\OAuth2\Client\Provider\Yahoo;
// @see https://github.com/stevenmaguire/oauth2-microsoft
use Stevenmaguire\OAuth2\Client\Provider\Microsoft;

if (!isset($_GET['code']) && !isset($_GET['provider'])) {
?>
<html>
<body>Select Provider:<br/>
<a href='?provider=Google'>Google</a><br/>
<a href='?provider=Yahoo'>Yahoo</a><br/>
<a href='?provider=Microsoft'>Microsoft/Outlook/Hotmail/Live/Office365</a><br/>
</body>
</html>
<?php
exit;
}

require '/var/www/html/mailer/vendor/autoload.php';

session_start();

$providerName = '';

if (array_key_exists('provider', $_GET)) {
    $providerName = $_GET['provider'];
    $_SESSION['provider'] = $providerName;
} elseif (array_key_exists('provider', $_SESSION)) {
    $providerName = $_SESSION['provider'];
}
if (!in_array($providerName, ['Google', 'Microsoft', 'Yahoo'])) {
    exit('Only Google, Microsoft and Yahoo OAuth2 providers are currently supported in this script.');
}

//These details are obtained by setting up an app in the Google developer console,
//or whichever provider you're using.
$clientId = 'my-client-id';
$clientSecret = 'my-client-secret';

//If this automatic URL doesn't work, set it yourself manually to the URL of this script
$redirectUri = 'https://localhost/mailer/vendor/phpmailer/phpmailer/get_oauth_token.php'; 
//$redirectUri = (isset($_SERVER['HTTPS']) ? 'https://' : 'http://') . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
//$redirectUri = 'http://localhost/PHPMailer/redirect';

$params = [
    'clientId' => $clientId,
    'clientSecret' => $clientSecret,
    'redirectUri' => $redirectUri,
    'accessType' => 'offline'
];

$options = [];
$provider = null;

switch ($providerName) {
    case 'Google':
        $provider = new Google($params);
        $options = [
            'scope' => [
                'https://mail.google.com/'
            ]
        ];
        break;
    case 'Yahoo':
        $provider = new Yahoo($params);
        break;
    case 'Microsoft':
        $provider = new Microsoft($params);
        $options = [
            'scope' => [
                'wl.imap',
                'wl.offline_access'
            ]
        ];
        break;
}

if (null === $provider) {
    exit('Provider missing');
}

if (!isset($_GET['code'])) {
    // If we don't have an authorization code then get one
    $authUrl = $provider->getAuthorizationUrl($options);
    $_SESSION['oauth2state'] = $provider->getState();
    header('Location: ' . $authUrl);
    exit;
// Check given state against previously stored one to mitigate CSRF attack
} elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) {
    unset($_SESSION['oauth2state']);
    unset($_SESSION['provider']);
    exit('Invalid state');
} else {
    unset($_SESSION['provider']);
    // Try to get an access token (using the authorization code grant)
    $token = $provider->getAccessToken(
        'authorization_code',
        [
            'code' => $_GET['code']
        ]
    );
    // Use this to interact with an API on the users behalf
    // Use this to get a new access token if the old one expires
    echo 'Refresh Token: ', $token->getRefreshToken();
}

Please check these things before submitting your issue:

php mailer v6.7.1

php version PHP 8.2.1

on linux mint
Your Composer dependencies require a PHP version ">= 7.4.0". You are running ' 7.2 comes up instead of 8.x

how do i fix? this is a bug as was fine other day ???

  • Read the error message you're seeing - it often tells you what is wrong, and may contain useful links & instructions
  • Make sure you're using the latest version of PHPMailer
  • Check that your problem is not dealt with in the troubleshooting guide, especially if you're having problems connecting to Gmail or GoDaddy
  • Include sufficient code to reproduce your problem
  • If you're having an SMTP issue, include the debug output generated with SMTPDebug = 2 set
  • If you have a question about how to use PHPMailer (rather than reporting a bug in it), tag a question on Stack Overflow with phpmailer, but search first!

Problem description

Code to reproduce

Debug output

It turns out i owed £1 and they didnt even email me about it they just shut it down but i learned some things today about debug and how to find if credentails are being rejected etc!

im glad to report ths is resolved and php mailer was not to blaim!