CodeIgniter: Trouble with Mailgun integration - 'not a trait' error

Help needed with CodeIgniter and Mailgun

I’m trying to set up email sending in my CodeIgniter project using the Mailgun library. I installed it with Composer, but I’m running into a weird error. When I try to use it, I get this message:

Fatal error: Sendmail cannot use Mailgun\Mailgun - it is not a trait

It happens in my Sendmail controller. I’ve been following the Mailgun docs and even watched some YouTube tutorials, but I’m still stuck. Here’s what my controller looks like:

class Sendmail extends CI_Controller
{
    use Mailgun\Mailgun;

    public function __construct()
    {   
        parent::__construct();
    }

    public function index()
    {
        try {
            $mgClient = new Mailgun('my_api_key');
            $domain = 'my_domain.mailgun.org';
            $result = $mgClient->sendMessage($domain, [
                'from'  => 'Test User <[email protected]>',
                'to'    => 'Me <[email protected]>',
                'subject' => 'Test Email',
                'text'  => 'Just testing Mailgun!'
            ]);
            return $result;
        } catch (\Throwable $th) {
            echo $th;
        }
    }
}

Am I missing something obvious? Any help would be great!

I see where the problem lies in your code. The ‘use’ statement for Mailgun is misplaced; it should be at the top of your file, not inside the class. To resolve this issue:

Place ‘use Mailgun\Mailgun;’ at the beginning of your file, before the class declaration. Within your index method, instantiate Mailgun using:

$mgClient = Mailgun::create(‘my_api_key’);

Also, ensure that Composer’s autoloader is properly included (for example, by adding require FCPATH . ‘./vendor/autoload.php’; at the start of your file or in CodeIgniter’s index.php). These changes should address the ‘not a trait’ error you are encountering.

I faced a similar challenge when integrating Mailgun with CodeIgniter. The issue is that Mailgun is not a trait; it’s a class that should be imported at the top of your PHP file. Move the line ‘use Mailgun\Mailgun;’ so that it appears before the class declaration. Also, ensure that Composer’s autoloader is loaded, for example using require FCPATH . ‘./vendor/autoload.php’; in your constructor or early in the file.

In your index method, instantiate Mailgun with Mailgun::create(‘your-api-key’) instead of using it as a trait. This should resolve the error you encountered.

hey man, ur problem is with the ‘use’ statement. it shouldnt be inside the class. move it to the top of ur file before the class declaration. also, make sure u got composer’s autoloader included (like require FCPATH . ‘./vendor/autoload.php’;). that should fix ur ‘not a trait’ error. good luck!