PHPMailer return errors rather than echoing

Working on a project that involves sending emails. I've been using PHPMailer for many years now, never let me down, is very easy to configure and setup for various different clients and settings.

This new project requires silent errors. We don't want the error messages ever appearing to the end-user, but we do want all errors logged. The issue with PHPMailer is that it ECHO's the error messages directly to the screen rather than passing it back to me. I prefer not to use the ob_* functions so I've managed to nail down what changes are required.

class.phpmailer.php

To begin we will start with the PHPMailer class itself, by default located in class.phpmailer.php I am using the latest version as of 2014-10-09 which is 5.2.9 so line numberings should line up properly

The error messages will not be accessible if $smtp is protected, we also need a variable to store the messages in:

# protected $smtp = null;
public $smtp = null;
public $phpmailer_errors = '';

Here we are adding a new case statement to the switch named 'variable', as we will be returning the data to the variable.

switch ($this->Debugoutput) {
    case 'error_log':

Change to:

switch ($this->Debugoutput) {
    case 'variable':
        $this->phpmailer_errors .= $str;
        break;
    case 'error_log':

class.smtp.php

Moving onto the SMTP class within class.smtp.php file.

public $smtp_errors = '';

Here we are adding a new case statement to the switch named 'variable', as we will be returning the data to the variable.

switch ($this->Debugoutput) {
    case 'error_log':

Change to:

switch ($this->Debugoutput) {
    case 'variable':
        $this->smtp_errors .= $str;
        break;
    case 'error_log':

Altogether

You may now permanently keep $mail->SMTPDebug = 2 or 1 within your code. Set $mail->Debugoutput = 'variable';

$mail->SMTPDebug = 2;
$mail->Debugoutput = 'variable';

if ($mail->Send()) {
    echo 'Successful';
} else {

    # Error messages are now contained to this accessible variable.
    # You can do whatever you wish with it. I wrote the errors to a file.
    echo $mail->smtp->smtp_errors;
}

If you're not using SMTP you can access the error messages through:

echo $mail->phpmailer_errors;

 

Print