0

Including Phpmailer In Kohana

by joecaps 14. March 2012 17:01

I am building a company website in Kohana and I'm trying to create a contact page for it. Kohana has some pretty cool validation support but lacks some sending e-mail support. So as a quick and dirty way to build a contact page that will send an email for the site administrator, I decided to use Phpmailer and Gmail as my mail server. To include Phpmailer classes in your Kohana controller, you need to create a folder one level down from your application folder and name it "vendor". Then put the phpmailer folder you've downloaded inside the vendor folder. The setup should look like this - Application->Vendor->Phpmailer. Thus all your phpmailer classes should be inside the phpmailer folder. This is how you include phpmailer classes in your Kohana controller:

<?php defined('SYSPATH') or die('No direct script access.');



class Controller_Page extends Controller {

  //include the phpmailer library
  protected static function include_library()
 { require_once Kohana::find_file( 'vendor/phpmailer', 'class.phpmailer' ); require_once Kohana::find_file( 'vendor/phpmailer', 'class.smtp' ); }

So your sendmail function inside the controller will look like this:

 

//function to send mail   
private function sendmail($to, $subject, $message, $fromname, $from='', $auth, $username, $password, $server)
{
    //include the library
    self::include_library();    
 try
     {
            
      
        
        $mailer = new PHPMailer();
        $mailer->AddAddress(trim($to));
              
        //set other information
        $mailer->IsSMTP();
          
        if(strlen(trim($from)) > 0)
        {
        $mailer->SetFrom($from, $fromname);
        }
        else
        {
       $mailer->FromName = $fromname; //should be the name of the sender
        }
           
        $mailer->Subject = $subject;
        $mailer->Body = $message;
        $mailer->SMTPAuth = $auth;
        $mailer->SMTPSecure = "tls";
        $mailer->Username = $username;
        $mailer->Password = $password;
  
        $mailer->Host = $server;
          
        $mailer->Port = 587;
         
        $mailer->Send();
          
        $mailer->SmtpClose();
        
        if ($mailer->IsError())
        {
            return 'false';
        }
        else
        {
            return 'true';
        }
       
     }
    catch(phpmailerException $ex)
    {
     return $ex->errorMessage(); 
    }
     catch (Exception $e) {
  return $e->getMessage(); //Boring error messages from anything else!
}

Hope I made myself clear. Until next time.......happy programming.

Tags: , ,

PHP

0

Building A PHP Error Handler With E-Mail Notification

by joecaps 2. July 2011 22:43

So I need to write a PHP class that'll send me an e-mail notification if an error(server-side) occurs on the chat application I'm building.  I decided to use PHPMailer library and Gmail as the mail server to implement the e-mail notification functionality for this error handler.  You can read PHPMailer's documentation here. Also you can download the library @ Sourceforge. I started the code by including the PHPMailer library on the top of the errorhandler class:

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);

class errorhandler {

//more code here.......

}
?>
To use Gmail server with PHPMailer, I need 3 important constants. These are the username, password, and the server name which is "smtp.gmail.com" for Gmail. So I declare the constants in my code like this:
 
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);
 
class errorhandler {
 
static $smtpserver = 'smtp.gmail.com';
static $username = 'yougmailusername';
static $password = 'yougmailpassword';

//more code here.......
 
}
?>
Now I write the function to send e-mail notification for errors inside the errorhandler class.
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);
  
class errorhandler {
  
static $smtpserver = 'smtp.gmail.com';
static $username = 'yougmailusername';
static $password = 'yougmailpassword';

private function sendmail($to, $subject, $message, $fromname, $from='', $auth, $username, $password, $server)
{

 try
        {

        $mailer = new PHPMailer();
    	$mailer->AddAddress(trim($to));
        	
        //set other information
        $mailer->IsSMTP();
        
        if(strlen(trim($from)) > 0)
        {
        $mailer->SetFrom($from, $fromname);
        }
        else 
        {
       $mailer->FromName = $fromname; //should be the name of the sender
        }
         
        $mailer->Subject = $subject;
        $mailer->Body = $message;
        $mailer->SMTPAuth = $auth;
        $mailer->SMTPSecure = "tls";
        $mailer->Username = $username;
        $mailer->Password = $password;

        $mailer->Host = $server;
        
        $mailer->Port = 587; 
       
        $mailer->Send();	
        
        $mailer->SmtpClose();
        
        }
	catch(Exception $ex)
	{
	
	}

}
 
//more code here.......
  
}
?>
Next I create a static function that will initialize or start the error handler class for performing its main duty. I called it "initialize".
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);
   
class errorhandler {
   
static $smtpserver = 'smtp.gmail.com';
static $username = 'yougmailusername';
static $password = 'yougmailpassword';
 
private function sendmail($to, $subject, $message, $fromname, $from='', $auth, $username, $password, $server)
{
 
 try
        {
 
        $mailer = new PHPMailer();
        $mailer->AddAddress(trim($to));
             
        //set other information
        $mailer->IsSMTP();
         
        //code shortened for clarity
        //more.......
        }
    catch(Exception $ex)
    {
     
    }
 
}
  


static function initialize($level = null)
	{
 
		if ($level == null)
		{
			$level = E_ALL;
		 }
		
		
		set_error_handler(array("errorhandler", "HandleError"), $level);
	 }
 
   
}
?>
Notice I called a static function "HandleError" which will be invoke everytime an error occurs on the code. This function should look like this:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);
    
class errorhandler {
    
static $smtpserver = 'smtp.gmail.com';
static $username = 'yougmailusername';
static $password = 'yougmailpassword';
  
private function sendmail($to, $subject, $message, $fromname, $from='', $auth, $username, $password, $server)
{
  
 try
        {
  
        $mailer = new PHPMailer();
        $mailer->AddAddress(trim($to));
              
        //set other information
        $mailer->IsSMTP();
          
        //code shortened for clarity
        //more.......
        }
    catch(Exception $ex)
    {
      
    }
  
}
   
 
 
static function initialize($level = null)
    {
     //more code here
     //code shortened for clarity
     }
  
   static function HandleError($code, $string, $file, $line, $context)
	{
		// ignore supressed errors
		if (error_reporting() == 0) 
		return;
      
      $err = "";
      $err .= "---- PHP Error ----\n";
      $err .= "Number: [" . $code . "]\n";
      $err .= "String: [" . $string . "]\n";
      $err .= "File: [" . $file . "]\n";
      $err .= "Line: [" . $line . "]\n\n";
      $err .= "Content: [" .$context."]\n\n";
      
      $to = 'admin@mysite.com';
      $subject = 'Error on '.$file;
      
      
     
      $this->sendmail($to,$subject,$err,'admin','',true,self::$username,self::$password,self::$smtpserver);
		
	}	
	

 
}
?>
The whole and finished errorhandler class should look like this:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.phpmailer.php);
require_once($_SERVER['DOCUMENT_ROOT'].'/phpmailerv5/class.smtp.php);
   
class errorhandler {
   
static $smtpserver = 'smtp.gmail.com';
static $username = 'yougmailusername';
static $password = 'yougmailpassword';

public function __construct() 
{  
   $this->initialize();
}
 
private function sendmail($to, $subject, $message, $fromname, $from='', $auth, $username, $password, $server)
{
 
 try
        {
 
        $mailer = new PHPMailer();
        $mailer->AddAddress(trim($to));
             
        //set other information
        $mailer->IsSMTP();
         
        if(strlen(trim($from)) > 0)
        {
        $mailer->SetFrom($from, $fromname);
        }
        else
        {
       $mailer->FromName = $fromname; //should be the name of the sender
        }
          
        $mailer->Subject = $subject;
        $mailer->Body = $message;
        $mailer->SMTPAuth = $auth;
        $mailer->SMTPSecure = "tls";
        $mailer->Username = $username;
        $mailer->Password = $password;
 
        $mailer->Host = $server;
         
        $mailer->Port = 587; 
        
        $mailer->Send(); 
         
        $mailer->SmtpClose();
         
        }
    catch(Exception $ex)
    {
     
    }
 
}
  
static function initialize($level = null)
    {
  
        if ($level == null)
        {
            $level = E_ALL;
         }
         
         
        set_error_handler(array("errorhandler", "HandleError"), $level);
     }
  
   static function HandleError($code, $string, $file, $line, $context)
    {
        // ignore supressed errors
        if (error_reporting() == 0) 
        return;
       
      $err = "";
      $err .= "---- PHP Error ----\n";
      $err .= "Number: [" . $code . "]\n";
      $err .= "String: [" . $string . "]\n";
      $err .= "File: [" . $file . "]\n";
      $err .= "Line: [" . $line . "]\n\n";
      $err .= "Content: [" .$context."]\n\n";
       
      $to = 'admin@mysite.com';
      $subject = 'Error on '.$file;
       
       
      
      $this->sendmail($to,$subject,$err,'admin','',true,self::$username,self::$password,self::$smtpserver);
         
    }   
 
}
?>
To test errorhandler class, change the constant values username and password to your real gmail username and password. Next add a reference to the file where errorhandler class lives. Also don't forget to change the "$to" variable on the sendmail function to the email address you want to receive notification. You should receive a message on your email account notifying about the error.
<?php
require_once('pathtoerrorhandler/errorhandler.php');

$errorhandler = new errorhandler();

//let's create an intentional error
trigger_error('An error occured........woooo');

//your actual code should go here
//it should always go after error handler object is created

?>

Tags:

PHP | web development

Powered by BlogEngine.NET 2.0.0.36
Original Design by Laptop Geek, Adapted by onesoft