Вывод ошибки phpmailer

I’m using the PHPMailer Class to send the smtp mails, but i need to trace log from PHPmailerException in mysql table,

Code :

 $mail = new PHPMailer(true);
    try {
    $mail->Host =$dmmodel->host;
    $mail->Username= $dmmodel->username;
    $mail->Password= $dmmodel->password;
    $mail->Mailer='smtp';
    $mail->Port=$dmmodel->port;
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = ($dmmodel->smtp_enableSSL==1?'ssl':($dmmodel->smtp_enableSSL==2 ? 'tls':''));
    $mail->SMTPDebug = 2;
    $mail->From = $dmmodel->email_from;
    $mail->FromName = $dmmodel->name_from;
    $mail->Subject    = $this->getContentBody($docmodel->content_subject,$docmodel->crm_base_contact_id,$_POST["taskid"],$postcode,$recall_by,$recall_dt,true);
    $mail->AddAddress($email[$i]);
    $mail->IsHTML(true); 
}
   catch (phpmailerException $e)
    {
         $msg = "Email Delivery failed -" .  $e->errorMessage();
         echo "Email not sent";
    } 

Where $msg variable has only message «SMTP Error: Could not authenticate»
but when i put alert , i am getting full message(as below) reason for this issue,

SMTP -> FROM SERVER:220 smtp.gmail.com ESMTP n3sm27565307paf.13 — gsmtp

SMTP -> FROM SERVER: 250-smtp.gmail.com at your service, [122.164.189.101]
250-SIZE 35882577
250-8BITMIME
250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
250-ENHANCEDSTATUSCODES
250-PIPELINING
250-CHUNKING
250 SMTPUTF8

SMTP -> ERROR: Password not accepted from server: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8 https://support.google.com/mail/?p=BadCredentials n3sm27565307paf.13 — gsmtp

SMTP -> FROM SERVER:250 2.1.5 Flushed n3sm27565307paf.13 — gsmtp

Email not sent

how can i store the above message in a variable ? Please can anyone help me to get this full message

To address OPs problem:

«PHPMailer also seems to echo the error out, so if there’s a problem, it just sends that info directly to the browser, essentially breaking any error handling I»m trying to do.»

It’s not obvious (to me anyway, being new to exceptions) that all exceptions will be fed to the output buffer. Should somebody turn on debugging in production, front end users might get a surprise. I didn’t want to leave that to chance. To add, the exception output was ending up in (and breaking) my JSON response, so it actually hindered my debugging.

My solution was to clean the buffer before returning the front end output. My use-case was a JSON response to a fetch API request, so before sending my output, I called ob_clean() to clean the buffer of any unwanted debugging data. For example:

ob_clean(); //clean the buffer
echo json_encode( $public_output ); //echo response to browser

I should clarify that this is a fallback for potentially unwanted output and should not be a substitute for disabling the debugging. On the contrary, I imagine this may even be problematic for a dev expecting to see debugging output in the browser.

$mail->SMTPDebug = SMTP::DEBUG_OFF;

Finally, useful error output can still be sent to the logs even with debugging disabled:

error_log( $mail->ErrorInfo );

PHPMailer Troubleshooting Wiki on GitHub

Use try & catch block to handle errors with PHPMailer in PHP.

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = SMTP::DEBUG_SERVER;
    $mail->isSMTP();
    $mail->Host       = 'smtp.example.com';
    $mail->SMTPAuth   = true;
    $mail->Username   = 'user@example.com';
    $mail->Password   = 'secret';
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
    $mail->Port       = 465;

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');

    //Content
    $mail->isHTML(true);
    $mail->Subject = 'Email subject';
    $mail->Body    = 'Your email message';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

You can also use the $mail->ErrorInfo method to display error info from the PHPMailer library.

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Your comment on this answer:

I use phpmailer to send mails and I would like to log the error from phpmailer when it occurs. I can only get a part of the error and not the whole error.

For logging I’m using monolog.

$log = new Logger('contact.php');
$log->pushHandler(new StreamHandler('./error.log',logger::WARNING));

As @Synchro suggested I’ve tried to use closure to capture the whole debug.

  if (!$err) {
      $mail = new PHPMailer(true);
      $mail->isSMTP();
      $mail->Host = 'maildev';
      $mail->SMTPDebug = 3;                                       // Enable verbose debug output
      $mail->SMTPAuth   = false;                                   // Enable SMTP authentication
      $mail->Debugoutput = 'html';
      $mail->SMTPAutoTLS = false; 
      $mail->Port       = '259';
      $mail->CharSet = 'utf-8';
      //$mail->setFrom($config['mail']['sendTo'], (empty($name) ? 'Contact form' : $name));
      $mail->setFrom($config['mail']['sendTo']);
      $mail->addAddress($config['mail']['sendTo']);
      $mail->addReplyTo($email, $name);
      $mail->isHtml();
      $mail->Subject = 'Contact form: ' . $subject;
      $mail->Body =  $query;
      $result="Thank you for connecting with us! We'll reply as soon as possible to you.";
      $form->clearPost();

    try {
      $debuglog = '';
      $mail->Debugoutput = function($str, $level) use ($debuglog) {
          $debuglog .= $str;
      };
      if (!$mail->send()) {
          $msg .= "Mailer Error: " . $mail->ErrorInfo;
          array_push($extra_info,['name',$name,$email,$query]);
          $log->error($debuglog, $extra_info);
      } else {
          $msg .= "Message sent!";
          $result="Thank you for connecting with us! We'll reply as soon as possible to you.";
      }
    } catch (phpmailerException $exp) {
      $debugError = $exp->errorMessage();
    }
  $log->error($debugError);

$debugError and $debuginfo are both NULL.

Errorinfo produces the next output in the browser:

2019-08-20 14:10:53 Connection: opening to maildev:259, timeout=300, options=array()
2019-08-20 14:10:53 Connection failed. Error #2: stream_socket_client(): unable to connect to maildev:259 (Connection refused) [/srv/http/vendor/phpmailer/phpmailer/src/SMTP.php line 326]
2019-08-20 14:10:53 SMTP ERROR: Failed to connect to server: Connection refused (111)
SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 

But in the log file I get only:

[2019-08-20 14:10:53] contact.php.ERROR: SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting ["172.27.0.1",["name","t","t@q.nl","werty"]] [] 

How can I log the full debugging message instead of only SMTP connect() failed. https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting?

Table of Contents

PHPMailer.php

Type Line Description
ERROR 402 Tag «see» with body «@see SMTP::DEBUG_OFF: No output» has error «PHPMailerPHPMailerSMTP::DEBUG_OFF:» is not a valid Fqsen.
ERROR 402 Tag «see» with body «@see SMTP::DEBUG_CLIENT: Client messages» has error «PHPMailerPHPMailerSMTP::DEBUG_CLIENT:» is not a valid Fqsen.
ERROR 402 Tag «see» with body «@see SMTP::DEBUG_SERVER: Client and server messages» has error «PHPMailerPHPMailerSMTP::DEBUG_SERVER:» is not a valid Fqsen.
ERROR 402 Tag «see» with body «@see SMTP::DEBUG_CONNECTION: As SERVER plus connection status» has error «PHPMailerPHPMailerSMTP::DEBUG_CONNECTION:» is not a valid Fqsen.
ERROR 402 Tag «see» with body «@see SMTP::DEBUG_LOWLEVEL: Noisy, low-level data output, rarely needed» has error «PHPMailerPHPMailerSMTP::DEBUG_LOWLEVEL:» is not a valid Fqsen.

POP3.php

Type Line Description
ERROR 75 Tag «see» with body «@see POP3::DEBUG_OFF: No output» has error «PHPMailerPHPMailerPOP3::DEBUG_OFF:» is not a valid Fqsen.
ERROR 75 Tag «see» with body «@see POP3::DEBUG_SERVER: Server messages, connection/server errors» has error «PHPMailerPHPMailerPOP3::DEBUG_SERVER:» is not a valid Fqsen.
ERROR 75 Tag «see» with body «@see POP3::DEBUG_CLIENT: Client and Server messages, connection/server errors» has error «PHPMailerPHPMailerPOP3::DEBUG_CLIENT:» is not a valid Fqsen.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Вывод ошибки mail php
  • Вывод ошибки golang
  • Вывод ошибки discord py
  • Вывод маток никот ошибки

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии