Search code examples
codeigniteremailcontrollers

Codeigniter, html email sending but variables are 'not defined'


I have a contact form that when submited, its sends an email and adds the data to the database as a backup.

When testing my email, i actually get the html email through (woo) but the variables that are being filled in are not supposedly defined in the view- what am i missing?

Controller

Form validation here----

If errors do this.....

If successful...

// set the response as successful
                $respond['result'] = 'true';
                $respond['success_message'] = $success_message;

// set field labels
                $data['message'] = $message;
                $data['first_name'] = $first_name;
                $data['email'] = $email;

                $html_email = $this->load->view('html_email', $data, true);

                // send email notification
                    $this->load->library('email');
                    $this->email->from('email-address', 'Email-address');
                    $this->email->to('email-address-here');                     
                    $this->email->subject('subject');
                    $this->email->message($html_email);         
                    $this->email->send();

                echo $this->email->print_debugger();

                // add contact message to the database
                $this->contact_model->insert_contact_message($curr_lang, $this->input->post('first_name'), $this->input->post('email'), $this->input->post('message'));

And in my html email is set up using tables and declare the variables as:

<?=$first_name?>
<?=$email?>
<?=$message?>

I know it's coming through as the styling is working but just the variables not pulling through.

When i look at my errors this is what i get from the html email:

A PHP Error was encountered
Severity: Notice

Message: Undefined variable: message    

Solution

  • You are missing parser. Here's how you do it:

    In your controller where you process email:

    function send_email()
       $this->load->library('parser');
       $this->load->library('email');
    
       $data = array(
          'name'  =>  $this->input->post('name'),
          'email' =>  $this->input->post('email'),
          'message' => $this->input->post('message)
       );
    
       $body = $this->parser->parse('path_to/email_view_template', $data, true);
    
       //set from, to etc.
       $this->email->message($body);
       $this->email->send();
    }
    

    Make sure your email config file is set to send html emails instead of plain text.

    Then in your email template you call variables like this:

    <p>You have just received email from {name}. You can contact {name} on {email}. {name} left a message saying: {message}</p>
    

    Let me know if any questions.