代码标志电子邮件错误处理

2022-08-30 20:03:09

CI Email send() 函数仅返回 true 或 false。有没有办法更详细地了解发送失败的原因?我使用的是 SMTP。


答案 1

您可以使用电子邮件调试器进一步检查发生的情况:

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

来自 Codeigniter 电子邮件类参考

如果需要将调试器输出作为字符串,则只需使用输出缓冲区捕获输出

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

在较新版本中,Codeigniter 需要为 email->send() 函数的 $auto_clear 参数显式 FALSE,以便不清除消息和调试,如果未能通过 FALSE,则有效地终止调试器函数。


答案 2

该函数将起作用,但它会在底部附加电子邮件标头和邮件。如果您只需要一个调试消息数组(包括成功消息和错误消息),则可以考虑按如下方式扩展 Email 类的功能:print_debugger()

<?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;
  }
}

您可能希望将其放在 ./application/libraries 文件夹中名为 MY_Email.php 的文件中。CodeIgniter 将自动识别此类的存在,并使用它而不是默认的类。

如果要获取调试消息的列表(数组),可以执行以下操作:

$this->email->get_debugger_messages();

如果要循环访问消息,并且不想包含以前尝试的调试器消息,则可以执行以下操作:

foreach ($email_addresses as $email_address)
{
  $this->email->to($email_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';
}

参考:https://www.codeigniter.com/user_guide/general/creating_libraries.html 的“扩展本机库”部分。


推荐