Retrieving logs from an SMTP server using PHPMailer

Often I see folks having trouble with PHPMailer in SMTP mode, but it is not always clear what the problem is, especially if the report merely is that “it doesn’t work”.

To understand what problem you are having, you can use the built-in logging facility in PHPMailer, something like this:

// Create the PHPMailer object here
// Add your config here

// Before the send
$smtpLogs = [];
$mail->SMTPDebug = 2;
$mail->Debugoutput = 'logHandler';

// Your send goes here
$mail->Send();

// After the send
print_r($mail->ErrorInfo);
printLogs($smtpLogs);

function logHandler($log, $level)
{
    global $smtpLogs;

    $smtpLogs[] = trim($log);
}

function printLogs(array $logs)
{
    echo implode("\n", $logs) . "\n";
}

Note that this will not help you if you are trying to use Sendmail.

The log output will show you if:

  • Your username or password is wrong
  • Your authentication is failing in some other way (e.g. Gmail requires extra settings changes on their side)
  • You are trying to use SSL/TLS, but the remote server certificates are invalid or self-signed
  • The SMTP server is otherwise not set up properly

If that still does not help you understand what the problem is, paste the SMTP conversation in your report here, in a formatted block. Please do not paste logs unformatted, as they are less readable that way.

1 Like