Search code examples
codeigniteremail-templates

I want to pass view to a string and to pass as a message body in email using codeigniter. Any suggestions?


I want to send email template when I register user. So I have created views for it so that can use different view as needed. Like for registration and forgot password two different views are there.

public function email($data, $type){

$smtp = $this->smtp_model->smtp_data();

$config['protocol']  = 'smtp';
$config['smtp_host'] = $smtp->host;
$config['smtp_port'] = $smtp->port;
$config['smtp_user'] = $smtp->username; 
$config['smtp_pass'] = $smtp->password;
$config['charset']   = 'utf-8';
$config['mailtype']  = 'html';
$config['newline']   = '\r\n';


$this->email->initialize($config);
$this->email->clear(TRUE);
$this->email->from($smtp->from_email, $smtp->from_name);
$this->email->to($data->email);
$this->email->subject(SITENAME.' - '.$type);

// Here it should return html from the view
$mail_message = $this->email_template($data, 'registration');

echo $mail_message;die;//but it is printing empty

$this->email->message($mail_message);
$this->email->send();
}

public function email_template($data, $type){

$email_body = $this->load->view('email/include/head');
// Below are the condition on basis of it view will be selected 
if($type == 'registration')
    $email_body = $this->load->view('email/user_registration', $data);
if($type == 'forgot_password')
    $email_body = $this->load->view('email/forgot_password', $data);

//Need to pass view to variabel which will be returned to above function
$email_body = $this->load->view('email/include/footer');

return $email_body;

}

Solution

  • Hope this help you :

    set third parameter of $this->load->view() to TRUE If you set the parameter to TRUE (boolean) it will return data. The default behavior is false,

    email_template method should be like this :

    public function email_template($data, $type)
    {
       $email_body = $this->load->view('email/include/head','',TRUE);
       if($type == 'registration')
       {
          $email_body += $this**strong text**->load->view('email/user_registration', $data,TRUE);
       }
       if($type == 'forgot_password')
       {
            $email_body += $this->load->view('email/forgot_password', $data,TRUE);
       }
    
       $email_body += $this->load->view('email/include/footer','',TRUE);
       return $email_body;
    }
    

    for more : https://www.codeigniter.com/user_guide/general/views.html#returning-views-as-data