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


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:

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

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


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:


and included


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 ?





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


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.