Viewed   88 times

Hi I am trying to use PHPMailer Library from GitHUB in my Codeigniter application.

I downloaded the code and unzipped in my applicationlibrary folder. So there I have a folder called vendor inside which resides the source code for PHPMailer.

Now I created a File named Bizmailer_Controller.php.

<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
* 
*/
class Bizmailer_Controller extends CI_Controller
{

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

        require "vendorphpmailerphpmailerPHPMailerAutoload";
        $this->Bizmailer = new PHPMailer();
        //Set the required config parameters
        $this->Bizmailer->isSMTP();                                      // Set mailer to use SMTP
        $this->Bizmailer->Host = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
        $this->Bizmailer->SMTPAuth = true;                               // Enable SMTP authentication
        $this->Bizmailer->Username = 'user@example.com';                 // SMTP username
        $this->Bizmailer->Password = 'secret';                           // SMTP password
        $this->Bizmailer->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
        $this->Bizmailer->Port = 465;    
        //return $api;
    }
}

Now in my controllers I am trying to load it like this :

$this->load->library('Bizmailer');
$mail = new Bizmailer();

And I Get this error :

An Error Was Encountered

Unable to load the requested class: Bizmailer

So Please guide me how I can load or integrate this library in Codeigniter.

 Answers

4

here is a guide

1. installing PHP Mailer

Download the latest PHPMailer Build from Github. You can find the project here

Click now on "clone or download" and download it as zip - as in the image below is shown.

The folder in the zip is called PHPMailer-master. Unzip this in your application/third_party/ folder and rename the folder to phpmailer. You should see something like this

2. PHP Mailer Library

Imho its best to create a library which handles your PHPMailer Object (Phpmailer_library.php) This library could look like

class Phpmailer_library
{
    public function __construct()
    {
        log_message('Debug', 'PHPMailer class is loaded.');
    }

    public function load()
    {
        require_once(APPPATH."third_party/phpmailer/PHPMailerAutoload.php");
        $objMail = new PHPMailer;
        return $objMail;
    }
}

3. Using this library in one of your controllers, models etc.

class Welcome extends CI_Controller {


    public function index()
    {
        $this->load->library("phpmailer_library");
        $objMail = $this->phpmailer_library->load();
    }
}

i think this should pretty much do the job. If you've any troubles, don't hesitate to ask ;)


Update 25.06.2018

Since the PHPMailer guys removed the autoloader you've two options now:

1.) via Composer

for those who didn't know - Codeigniter supports Composer - you simply have to activate the autoload - you can find this in your config.php

$config['composer_autoload'] = true;

For more informations take a look here

After that - run composer like

composer require phpmailer/phpmailer

You now should have within your application/vendor folder the phpmailer files.

The library should look like

class Phpmailer_library
{
    public function __construct()
    {
        log_message('Debug', 'PHPMailer class is loaded.');
    }

    public function load()
    {
        $objMail = new PHPMailerPHPMailerPHPMailer();
        return $objMail;
    }
}

2.) download

follow step 1

The library should look like

class Phpmailer_library
{
    public function __construct()
    {
        log_message('Debug', 'PHPMailer class is loaded.');
    }

    public function load()
    {
        require_once(APPPATH.'third_party/phpmailer/src/PHPMailer.php');
        require_once(APPPATH.'third_party/phpmailer/src/SMTP.php');

        $objMail = new PHPMailerPHPMailerPHPMailer();
        return $objMail;
    }
}

and everything else should remain the same

Monday, October 3, 2022
 
2

You're using SMTP authentication but you're not actually defining any host, which is required:

Ex: $mail->Host = "smtp.example.com";

Put that changed with your domain after $mail->isSMTP();.

Also, optionally, you can provide a username and password like this, if you need:

$mail->Username = 'username'; $mail->Password = 'password';

Monday, December 5, 2022
 
5

According to PHPMailer's owner, he helped me and eventually solve this problem! It should happen for every programmer and when I fixed it I surprised! The problem was about the class name! I define PHPMailer class as Library's class and it's not allowed! So intead of code above (That I'v mentioned) I should try this and it works fine as well :

class Sendingmail {
     public function singleMail($setFromTitle,$setToMail,$setToName,$setSubject,$setMessage) {
          // Rest of codes
     }
}

So don't named your class to PHPMailer or something like this which probably has defined in core functions!

Wednesday, November 16, 2022
 
lenk
 
2

Install Doctrine

(The following instructions are modified from: Doctrine 2 ORM’s documentation - Installation and Configuration)

Doctrine can be installed with Composer:

  1. From your command line (e.g. Windows: Start > cmd), change to the folder where the files should be installed (e.g. htdocs/my_project).

  2. Use Composer to install the files:

    a. run C:>composer install doctrine/orm

    or:

    b. Define the following requirement in your composer.json file:

    {
    "require": {
        "doctrine/orm": "*"
      }
    }
    

    and then call composer install from your command line.

Composer will install a folder vendor with numerous sub-folders and several hundred php files. Move this vendor folder into your CodeIgniter application tree. For simplicity, you could put it here:

/application
    /config
    /controllers
    /libraries
       Doctrine.php <-- the doctrine bootstrap/wrapper file
    /third_party
/vendor  <-- the folder installed by Composer. don't touch the files or folders below it -- install all together as one happy family.
    /bin
    /composer
    /doctrine
    /symfony
    autoload.php  <-- Doctrine.php opens this to load its files

then in your library file Doctrine.php (see below) you would just:

require_once FCPATH . 'vendor/autoload.php';  // FCPATH is a CI constant specifies the path to the front controller.

You could also install all the folders and files contained inside vendor elsewhere, say in third_party and adjust your Doctrine.php accordingly.


Integrating with CodeIgniter

(The following instructions are modified from: Doctrine 2 ORM’s documentation - Integrating with CodeIgniter)

  1. Create your Doctrine library: In your folder system/application/libraries, create a file named Doctrine.php and copy/paste the following code into the file. This is going to be your wrapper/bootstrap for the Doctrine2 entity manager.

    Your Doctrine.php library file should look like this (you may customize it to your needs):

    <?php
    /**
    * Doctrine 2.4 bootstrap
    *
    */
    
    use DoctrineCommonClassLoader,
       DoctrineORMConfiguration,
       DoctrineORMEntityManager,
       DoctrineCommonCacheArrayCache,
       DoctrineDBALLoggingEchoSQLLogger;
    
    
    class Doctrine {
    
       public $em = null;
    
       public function __construct()
       {
         // load database configuration from CodeIgniter
         require_once APPPATH.'config/database.php';
    
        // load Doctrine
        require_once FCPATH . 'vendor/autoload.php';
    
        // or, if you installed another way, you could:
        // require_once APPPATH.'third_party/Doctrine/Common/ClassLoader.php';
    
        // load the Doctrine classes        
        $doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'libraries');
        // or, if installed in third_party: 
        // $doctrineClassLoader = new ClassLoader('Doctrine',  APPPATH.'third_party');
        $doctrineClassLoader->register();
        // load the entities
        $entityClassLoader = new ClassLoader('Entities', APPPATH.'models');
        $entityClassLoader->register();
        // load the proxy entities
        $proxiesClassLoader = new ClassLoader('Proxies', APPPATH.'models/proxies');
        $proxiesClassLoader->register();
        // load Symfony2 classes
        // this is necessary for YAML mapping files and for Command Line Interface (cli-doctrine.php)
        $symfonyClassLoader = new ClassLoader('Symfony',  APPPATH.'third_party/Doctrine');
        $symfonyClassLoader->register();
    
        // Set up the configuration
        $config = new Configuration;
    
        // Set up caches
        if(ENVIRONMENT == 'development'):  // set environment in index.php
            // set up simple array caching for development mode
            $cache = new DoctrineCommonCacheArrayCache;
        else:
            // set up caching with APC for production mode
            $cache = new DoctrineCommonCacheApcCache;  
        endif;
        $config->setMetadataCacheImpl($cache);
        $config->setQueryCacheImpl($cache);
    
        // set up annotation driver
        $driver = new DoctrineORMMappingDriverPHPDriver(APPPATH.'models/Mappings');
        $config->setMetadataDriverImpl($driver);
    
        // Proxy configuration
        $config->setProxyDir(APPPATH.'/models/Proxies');
        $config->setProxyNamespace('Proxies');
    
        // Set up logger (recommended to remove for production)
        $logger = new EchoSQLLogger;
        $config->setSQLLogger($logger);
    
        $config->setAutoGenerateProxyClasses( TRUE ); // only for development
    
        // Database connection information
        $connectionOptions = array(
            'driver' => 'pdo_mysql',
            'user' =>     $db['default']['username'],
            'password' => $db['default']['password'],
            'host' =>     $db['default']['hostname'],
            'dbname' =>   $db['default']['database']
        );
    
        // Create EntityManager, and store it for use in our CodeIgniter controllers
        $this->em = EntityManager::create($connectionOptions, $config);
      }
    }
    
  2. Load the doctrine library: either autoload your Doctrine library by adding it to the array in your application/config/autoload.php file:

    '$autoload[‘libraries’] = array(‘doctrine’);`

or load it manually in your controller like any other library by using:

$this->load->library('doctrine');

If you installed Doctrine.php in applications/third_party, you would use:

$autoload[‘libraries’] = array('third_party/doctrine');

or

$this->load->library('third_party/doctrine');

An example controller is provided below in What's next.


Setting up the Command Line Tool

Doctrine ships with a number of command line tools that are very helpful during development.

Check if these lines exists in the Doctrine.php file, to load Symfony classes for using the Command line tools (and for YAML mapping files):

$symfonyClassLoader = new ClassLoader('Symfony', APPPATH.'third_party/Doctrine');
$symfonyClassLoader->register();

You need to register your applications EntityManager to the console tool to make use of the tasks by creating a cli-doctrine.php file in the application directory with the following content:

 <?php

 /**
 * Doctrine CLI bootstrap for CodeIgniter
 *
 */

 define('APPPATH', dirname(__FILE__) . '/');
define('BASEPATH', APPPATH . '/../system/');
define('ENVIRONMENT', 'development');

 require APPPATH.'libraries/Doctrine.php';

$doctrine = new Doctrine;
$em = $doctrine->em;

 $helperSet = new SymfonyComponentConsoleHelperHelperSet(array(
    'db' => new DoctrineDBALToolsConsoleHelperConnectionHelper($em->getConnection()),
    'em' => new DoctrineORMToolsConsoleHelperEntityManagerHelper($em)
));

 DoctrineORMToolsConsoleConsoleRunner::run($helperSet);

 ?>

Now run this script through the PHP command-line and should see a list of commands available to you.

php cli-doctrine.php

Generate mapping classes from database:

php cli-doctrine.php orm:convert-mapping --from-database annotation models/Entities

if you get this error: Fatal error: Call to undefined function DoctrineCommonCacheapc_fetch() install the APC extension for PHP:

sudo apt-get install php-apc
sudo /etc/init.d/apache2 restart

For production mode: Doctrine recommends changing the following settings in Doctrine.php: - use a real caching system like APC - disable EchoSqlLogger - turn off autoGenerateProxyClasses


What's next

To use Doctrine in CI, call it from a controller, for example:

application/controllers/my_controller.php:

function doctrine_orm()
{
    $this->load->library('Doctrine');
    $em = $this->doctrine->em;

    // do Doctrine stuff
    $productRepository = $em->getRepository('Product');
    $products = $productRepository->findAll();
    foreach ($products as $product):
        echo sprintf("-%sn", $product->getName());
    endforeach;
}

Before doing any Doctrine stuff, however, you must first map your database tables to Doctrine "entities". Learn how here: https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/tutorials/getting-started.html

Sunday, September 25, 2022
3

You need to define variables before you use them!

require "modules/mailer.php";
$email_send = new mailSend();

$subject = "Please verify email!";
$message = "Thanks for signing up!<br>
            Please click on the link below:<br><br>
            <a href=".$url.">".$url."</a>";
$email_send->sendMail($email,$message,$subject);

To get PHPMailer to throw exceptions, you need to ask it, by passing true to the constructor:

$mail = new PHPMailerPHPMailerPHPMailer(true);

Now to get responses out of your class, you need to return something, so change the end of your send function to this:

$result = [];
$mail->send();
    $result['success'] = true;
    $result['message'] = "Mail sent.";
} catch (Exception $e) {
    $result['success'] = false;
    $result['message'] = "Failed. Mailer error: {$mail->ErrorInfo}";
}
return $result;

Then when you call your function:

$result = $email_send->sendMail($email,$message,$subject);
if ($result['success']) {
    echo $result['message'];
    //Do whatever else you want to do on success
} else {
    echo $result['message'];
}
Saturday, August 6, 2022
 
marios
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :