What is the simplest way to use an external php library in a custom magento 2 module?

181

I am new on magento I am currently working on a custom module for magento2 and I want to use an external php library (PHPMailer) within a Block file.

my project files structure:

ModuleFolder
---etc
.
.
---Block
------- Main.php
---lib
------- PHPMailer
.
.

I tried to include the PHPMailer class within my block main.php using:

require_once(__DIR__."/../lib/PHPMailer/src/PHPMailer.php");

and for the class declaration i used :

$mail = new PHPMailer();

also i tried to include the PHPMailer library in the Block folder and nothing works

it always returns :

PHPMailer class is not found in /...../Block/Main.php

And when i tried to put the PHPMailer.php directly in the Block folder like this:

---Block
-----Main.php
-----PHPMailer.php

and included

require_once(__DIR__."/PHPMailer.php");

it returns: cannot declare PHPMailer class in Main.php because the name is already in use in PHPMailer.php

I installed the latest version of PHPMailer from github: https://github.com/PHPMailer/PHPMailer

And i decided to use it because it is so easy and straightforward.

So how can i use this library and what is the best way for this ?

Thanks!

66

Answer

Solution:

Magento 2 is built with Composer as a first class citizen. You should use Composer to install PHPMailer as well: https://github.com/PHPMailer/PHPMailer#installation--loading

composer require phpmailer/phpmailer

This means the PHPMailer class autoloading is taken care of by Composer, and you can use it immediately in your project code:

$mail = new \PHPMailer\PHPMailer\PHPMailer();

People are also looking for solutions to the problem: php - why would $stmt->execute() print_r = Object in ajax

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.