当前位置: 首页 > 知识库问答 >
问题:

PHPMailer异常错误

谷梁宏恺
2023-03-14

我已经为发送电子邮件编写了自己的代码点火器模型。直到最近我开始出现这个错误,一切都很好:

致命错误:无法在/home/mysite/public\u html/subdir/application/libraries/phpmailer/class中重新声明类phpmailerException。phpmailer。php在线2319

我正在使用:

代码点火器2 PHP点火器5.1

我尝试了以下方法来解决它:

  • 添加了$mail-

以下是我的控制器方法(公司/联系人),它调用我的模型(消息\模型):

    function contact()
    {
        //Do settings.
        $this->options->task='email';
        $this->options->change = 'sent';
        $this->options->form_validation='';
        $this->options->page_title='Contact Us';

        //Import library
        include_once('application/libraries/recaptcha/recaptchalib.php');//Include recaptcha library.

        //Keys for recaptcha, stored in mainconfig file.
        $this->options->publickey = $this->config->item('recaptcha_public');
        $this->options->privatekey = $this->config->item('recaptcha_private');      

        //Form validation
        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');
        $this->form_validation->set_rules('name_field','Name of problem','trim|required|min_length[3]|max_length[100]');
        $this->form_validation->set_rules('desc_field','Description','trim|required|min_length[10]|max_length[2000]');
        $this->form_validation->set_rules('email_field','Your email address','trim|required|valid_email');
$this->form_validation->set_rules('recaptcha_response_field','captcha field','trim|required|callback__check_recaptcha');

//If valid.
        if( $this->form_validation->run() )
        {
  //Set email contents.
            $message="This is a message from the contact form on ".$this->config->item('site_name')."<br /><br />";
            $message.=convert_nl($this->input->post('desc_field'));
            $message.="<br /><br />Reply to this person by clicking this link: <a href=\"mailto:".$this->input->post('email_field')."\">".$this->input->post('name_field')."</a><br /><br />";

  $options = array('host'=>$this->config->item('email_host'),//mail.fixilink.com
            'username'=>$this->config->item('email_username'),
            'password'=>$this->config->item('email_password'),
            'from_name'=>$this->input->post('name_field'),
            'to'=>array($this->config->item('email_to')=>$this->config->item('email_to') ),
            'cc'=>$this->config->item('email_cc'),
            'full_name'=>$this->input->post('name_field'),
            'subject'=>'Email from '.$this->config->item('site_name').' visitor: '.$this->input->post('name_field'),
            'message'=>$message,
            'word_wrap'=>50,
            'format'=>$this->config->item('email_format'),
            'phpmailer_folder'=>$this->config->item('phpmailer_folder')
            );

  //Send email using own email class and phpmailer.
            $result = $this->message_model->send_email($options);

            //Second email to sender
  //Set email contents.
            $message="Thank you for your enquiry, we aim to get a reply to you within 2 working days.  In the meantime, please do follow us on www.facebook.com/autismworksuk";

            $options = array('host'=>$this->config->item('email_host'),//mail.fixilink.com
            'username'=>$this->config->item('email_username'),
            'password'=>$this->config->item('email_password'),
            'from_name'=>$this->input->post('name_field'),
            'to'=>$this->input->post('email_field'),
            'full_name'=>$this->input->post('name_field'),
            'subject'=>'Email from '.$this->config->item('site_name'),
            'message'=>$message,
            'word_wrap'=>50,
            'format'=>$this->config->item('email_format'),
            'phpmailer_folder'=>$this->config->item('phpmailer_folder')
            );

  //Send email using own email class and phpmailer.
            $result = $this->message_model->send_email($options);           

            //Set result.    
            if($result==-1)
                $this->session->set_flashdata('result', ucfirst($this->options->task).' was not '.$this->options->change.' because of a database error.');
            elseif($result==0)
                $this->session->set_flashdata('result', 'No changes were made.');
            else
                $this->session->set_flashdata('result', ucfirst($this->options->task).' was '.$this->options->change.' successfully.');

            //Redirect to completed controller.
            redirect('completed');
        }

//Validation failed or first time through loop.
        $this->load->view('company/contact_view.php',$this->options);
    }

这是我的模型发送电子邮件的方法。它曾经工作,但没有任何变化,我可以想到现在我得到一个异常错误:

    function send_email($options=array())
    {
        if(!$this->_required(array('host','username','password','from_name','to','full_name','subject','message'),$options))//check the required options of email and pass aggainst provided $options.
          return false;

        $options = $this->_default(array('word_wrap'=>50,'format'=>'html','charset'=>'utf-8'),$options);

try
{        
  if(isset($options['phpmailer_folder']))
    require($options['phpmailer_folder']."/class.phpmailer.php");
  else
    require("application/libraries/phpmailer/class.phpmailer.php");//Typical CI 2.1 folder.

  $mail = new PHPMailer();
  $mail->MailerDebug = false;

  //Set main fields.
  $mail->SetLanguage("en", 'phpmailer/language/');
  $mail->IsSMTP();// set mailer to use SMTP
  $mail->SMTPDebug  = 0;  

  $mail->Host =     $options['host'];
  $mail->SMTPAuth = TRUE;     // turn on SMTP authentication
  $mail->Username = $options['username'];
  $mail->Password = $options['password'];
  $mail->FromName = $options['from_name'];//WHo is the email from.
  $mail->WordWrap = $options['word_wrap'];// Set word wrap to 50 characters default.
  $mail->Subject =  $options['subject'];
  $mail->Body    =  $options['message'];        
  $mail->CharSet =  $options['charset'];

  //From is the username on the server, not sender email.
  if(isset($options['from']))
    $mail->From = $options['from'];
  else
    $mail->From = $mail->Username;  //Default From email same as smtp user

  //Add reply to.
  if(isset($options['reply_to']))
    $mail->AddReplyTo($options['reply_to'], $options['from']);

  if(isset($options['sender']))
    $mail->Sender = $options['sender'];

  //Add recipients / to field (required)
  if(is_array($options['to']))
  {
    foreach($options['to'] as $to =>$fn)
      $mail->AddAddress($to, $fn);
  }
  else
  {
    $mail->AddAddress($options['to']); //Email address where you wish to receive/collect those emails.
  }

  //Add cc to list if exists. Must be an array
  if(isset($options['cc']))
  {
    if(is_array($options['cc']))
    {
      foreach($options['cc'] as $to =>$fn)
        $mail->AddCC($to, $fn);
    }
    else
    {
      log_message('debug', '---->CC field must be an array for use with Message_Model.');
    }
  }

  //Add bcc to list if exists. Must be an array
  if(isset($options['bcc']))
  {
    if(is_array($options['bcc']))
    {
      foreach($options['bcc'] as $to =>$fn)
        $mail->AddBCC($to, $fn);
    }
    else
    {
      log_message('debug', '---->BCC field must be an array for use with Message_Model.');
    }
  }

  //Alternative text-only body.
  if(isset($options['alt_body']))
    $mail->AltBody=$options['alt_body'];
  else
    $mail->AltBody = htmlspecialchars_decode( strip_tags( $options['message'] ),ENT_QUOTES );//Strip out all html and other chars and convert to plain text.

  //Plain/html format.
  if(isset($options['format']))
  {
    if($options['format']=='html')
      $mail->IsHTML(true);                                  // set email format to HTML
  }     

  //Send email and set result.
  $return['message']='';

  if(!$mail->Send())
  {
   $return['message'].= "Message could not be sent.<br />\n";
   $return['message'].= "Mailer Error: " . $mail->ErrorInfo."\n";
   $return['result'] = 0;
  }
  else
  {
    $return['message'].= "Message has been sent successfully.\n";
    $return['result'] = 1;
  }
}
catch (phpmailerException $e)
{
  log_message('error', '---->PHPMailer error: '.$e->errorMessage() );
}
catch (Exception $e) 
{
  log_message('error', '---->PHPMailer error: '.$e->errorMessage() );
}
        return $return;
    }

共有3个答案

赖鸿羲
2023-03-14

require_once(class.phpmailer.php)更好。

穆克什是对的,require_once将解决Sift Exchange的答案#1。但是,不需要检查类是否存在,因为require_once这样做。

龚迪
2023-03-14

基本上有两件事正在发生:

>

  • 您在某处两次“包含”PHP代码,导致第二次生成重新声明错误

    除了您的模型之外,您还在其他地方使用“phpmailerException”。您是否尝试过在IDE中为所有对“phpmailerException”的调用执行“全部查找”-也许您在另一个区域中使用了该名称作为另一个异常?

  • 濮波
    2023-03-14
    if (!class_exists("phpmailer")) {
    require_once('PHPMailer_5.2.2/class.phpmailer.php');
    }
    

    此代码将100%清除此问题。。

     类似资料:
    • 问题内容: 我正在尝试将PHPMailer用于一个小项目,但对于此软件的错误处理有些困惑。希望有人有经验。设置电子邮件后,我将使用: 哪个工作正常,或多或少。问题是当出现错误时,PHPMailer似乎也会回显该错误,因此,如果出现问题,它将直接将该信息发送到浏览器,从本质上打破了我试图做的任何错误处理。 有没有办法使这些消息静音?它没有抛出异常,只是打印出错误,在我的测试案例中是: 它的意思是一个

    • 目录表 错误 try..except 处理异常 引发异常 如何引发异常 try..finally 使用finally 概括 当你的程序中出现某些 异常的 状况的时候,异常就发生了。例如,当你想要读某个文件的时候,而那个文件不存在。或者在程序运行的时候,你不小心把它删除了。上述这些情况可以使用异常来处理。 假如你的程序中有一些无效的语句,会怎么样呢?Python会引发并告诉你那里有一个错误,从而处理

    • 忽略on_member_remove Traceback中的异常(最近一次调用为last):文件“C:\Users\Filbert\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\Local Packages\Python38\site Packages\discord\clie

    • 原因:异常[EclipseLink-6076](Eclipse持久性服务-2.5.0.v20130507-3faac2b):org。日食坚持不懈。例外。QueryException异常描述:对象比较只能用于OneToOneMappings。其他映射比较必须通过查询键或直接属性级比较来完成。映射:[org.eclipse.persistence.mappings.DirectToFieldMappi

    • 我在Eclipse中尝试Apache HTTP客户端库 下面的代码片段检查了异常并需要处理。 日蚀给出了3条建议 > Add throws Exception-(工作正常) 用尝试捕捉包围- (也工作正常) 用try/multicatch环绕 第三个选项给出错误 客户端协议异常已经被替代的IO异常捕获 我看到了的源代码,它。据我所知,在捕获多个异常时,我们可以在更具体的异常下捕获更一般的异常。因此

    • 错误处理是每个编程语言都要考虑的一个重要话题。在Go语言的错误处理中,错误是软件包API和应用程序用户界面的一个重要组成部分。 在程序中总有一部分函数总是要求必须能够成功的运行。比如strconv.Itoa将整数转换为字符串,从数组或切片中读写元素,从map读取已经存在的元素等。这类操作在运行时几乎不会失败,除非程序中有BUG,或遇到灾难性的、不可预料的情况,比如运行时的内存溢出。如果真的遇到真正