Search code examples
phpcodeigniteremailcodeigniter-2

code igniter email function


I have a small question, I have a perfectly working function written in code igniter for sending emails. But what I wanted to know if its possible that if the email sending function has some problems sending email how can I make sure that the other functions in the controller are still running. To be precise, this is my controller.

public function CreateMoney($token){        
        if ($this->input->is_ajax_request()){
            $alldata = json_decode(file_get_contents('php://input'), true);
            $userid = $this->myajax->getUserByAuth($token);
            if ($userid){

                /* some code here */


                $this->db->trans_commit();

                $this->sendEmail();

               /* some more code here */

                $this->output->set_content_type('application/json');
                $this->output->set_output(json_encode($invoice));


    } else {
                return $this->output->set_status_header('401', 'Could no identify user!');
    }
        } else {
            return $this->output->set_status_header('400', 'Request not understood as an Ajax request!');
        }    
}

So when I click a button it runs this controller code, and then when it goes to the email function it runs this code,

public function sendEmail() {
    //fetch tha data from the database 
        $this->load->model('payment_plan');
        $foo = $this->payment_plan->getInfoToNotifyBorrowerForNewLoan();
        $result = json_decode(json_encode($foo[0]), true);

        $this->load->library('email');
        $config['protocol'] = 'smtp';

        $config['smtp_host'] = 'ssl://smtp.gmail.com';

        $config['smtp_port']    = '465';

        $config['smtp_timeout'] = '7';

        $config['smtp_user']    = '*******';

        $config['smtp_pass']    = '*******';

        $config['charset']    = 'utf-8';

        $config['newline']    = "\r\n";

        $config['mailtype'] = 'text'; // or html

        $config['validation'] = TRUE; // bool whether to validate email or not      

        $this->email->initialize($config);

        $this->email->from('*******', '*******');
        $this->email->to($result['Email']);
        $this->email->subject('*******');

        $name               = $result['Fullname'];

        $this->email->message(
            'Hello! '.$name."\n"."\n"



            );  
    $returnvalue = $this->email->send();

    if(!$returnvalue) {
      return false;
    } else {
     $data = array('notified_borrower' => date('Y-m-d'));
     $this->db->update('payment_plan', $data);
     return true;
    }
}

So my question is if there is an error in sending the email, like i remove

$returnvalue = $this->email->send();

from the email function, then there is no sending an email, so how can my controller CreateMoney still run the other some codes even if the email function fails. I tried it by putting return false at the bottom of email function but still when I make a error in the email function on purpose the whole controller function stops. So need a way to make sure that the controller function keeps running even if there is a problem with the email function


Solution

  • This is exactly what try/catch blocks are for. You'll find some more information on Exceptions here. Here's some dummy code:

    In your CreateMoney():

    $log = array();
    try {
        $this->sendEmail();
    } catch(Exception $e) {
        $log[] = $e->getMessage();
        // just some stupid dummy code
        // do sth. more useful with it!
    }
    
    // afterwards
    if (count($log) > 0) {
        // some error occured
        // db has not been updated
    }
    

    In your sendEmail() function:

    // sth. went wrong here
    if (!$this->email->send())
        throw new Exception("Could not send email");
    else {
        $data = array('notified_borrower' => date('Y-m-d'));
        $this->db->update('payment_plan', $data);
    }
    

    This way, an email sending can fail and the controller runs nevertheless.