Codeigniter Email error handling

2020-02-12 01:37发布

问题:

The CI Email send() function only returns true or false. Is there a way to get a more detailed reason as to why a sending failed? I'm using SMTP.

回答1:

You can further inspect what happened by using the email debugger:

$r = $this->send(FALSE);
if (!$r)
  $this->email->print_debugger()
  ;

From the Codeigniter Email Class Reference.

If you need the debugger output as a string, you can just catch the output with an output buffer:

$errors = array();
... # Loop
$r = $this->send(FALSE);
if (!$r) {
  ob_start();
  $this->email->print_debugger();
  $error = ob_end_clean();
  $errors[] = $error;
}
... # Loop end

Codeigniter in more recent versions requires an explicit FALSE for the $auto_clear parameter of the email->send() function in order to not clear the message and the debugging, effectively killing the debugger function if you fail to pass the FALSE.



回答2:

The print_debugger() function will work but it appends the e-mail header and message at the bottom. If all you want is an array of the debug message (which include both success and error messages), you could consider extending the functionality of the Email class as follows:

<?php

class MY_Email extends CI_Email
{

  public function clear_debugger_messages()
  {
    $this->_debug_msg = array();
  }

  public function get_debugger_messages()
  {
    return $this->_debug_msg;
  }
}

You'd want to place this in a file named MY_Email.php in your ./application/libraries folder. CodeIgniter will automatically recognize the existence of this class and use it instead of it's default one.

When you want to get a list (array) of debug messages, you can then do this:

$this->email->get_debugger_messages();

If you're looping through messages and don't want to include debugger messages from previous attempts, you can do this:

foreach ( $email_addresses as $email_address )
{
  $this->email->to($emai_address);

  if ( ! $this->email->send() )
  {
    echo 'Failed';

    // Loop through the debugger messages.
    foreach ( $this->email->get_debugger_messages() as $debugger_message )
      echo $debugger_message;

    // Remove the debugger messages as they're not necessary for the next attempt.
    $this->email->clear_debugger_messages();
  }
  else
    echo 'Sent';
}

Reference: "Extending Native Libraries" section of https://www.codeigniter.com/user_guide/general/creating_libraries.html.



回答3:

You could check your mail logs. If the mail errors out then you should have a record saying why in there.

I'm not sure where they will be located though it depends on your system.