Home > OS >  Sending Email By Loading View File in CI4
Sending Email By Loading View File in CI4

Time:01-01

I'm facing an issue with my code. I'm actually loading view using View(), but instead of sending email it rendering the view. I'm way much confused why its happening? Here is my code.

namespace App\Libraries;

use App\Libraries\Options; // Loading Options Library

class CustomEmail
{
    private $email;
    private $option;


    public function setProtcols()
    {
        $this->option = new Options(); // Loading Options Library
        $this->option->load(); // Loading Options


        $this->email = \Config\Services::email();

        $config['charset']  = 'utf-8';
        $config['wordWrap'] = true;
        $config['mailType'] = 'html';

        if ($this->option->key->smtp_active == 1) {
            $config['protocol'] = 'smtp';
            $config['SMTPHost'] = $this->option->key->smtp_host;
            $config['SMTPUser'] = $this->option->key->smtp_username;
            $config['SMTPPass'] = $this->option->key->smtp_password;
            $config['SMTPPort'] = $this->option->key->smtp_port;
            $config['SMTPCrypto'] = $this->option->key->smtp_encryption;
        }

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

    public function sendMail($to, $subject, $data, $view = 'emails/default')
    {
        $this->setProtcols();
        $this->email->clear();

        $data = array_merge($data, [
            'base_url'                      => base_url(),
            'web_name'                      => $this->option->key->web_name,
            'address'                       => $this->option->key->address,
            'company_registration_number'   => $this->option->key->company_registration_number,
            'whatsapp_number'               => $this->option->key->whatsapp_number,
            'phone_number'                  => $this->option->key->phone,
        ]);


        $body = view($view, $data);
        
        $this->email->setFrom($this->option->key->email, $this->option->key->web_name);
        $this->email->setTo($to);
        $this->email->setSubject($subject);
        $this->email->setMessage($body);

        if ($this->email->send()) {
            return true;
        } else {
            return false;
        }
    }
}

The expected output is to send email with the HTML in the view by not rendering/displaying the view.

CodePudding user response:

There was an undefined variable inside my view, I just defined it and its start working.

It was something which wasn't leaving any error log, even in debug mode I wasn't leaving any traces.

I tried to see the last of the response, the HTML code I was getting! and were ending some where in the middle of view, I just go to that view file saw a variable was there, I further checked my library and I came to know that I was passing $phone while in view I wrote $number in my view.

I hope this will help others.

  • Related