Using CodeIgniter’s Email library separately

I’ve developed my own libraries for rapid development of PHP applications. Email library is one area which I didn’t feel like developing a library for. Just then, I remembered how simple and robust CodeIgniter’s Email class was. I decided to try it on my own script. It was not at all difficult to get it working. It just commented out few lines of codes and voila! I was able to send my first email.

Those who are in need of a email library could use this simple library separately. I’ll guide you through the whole process step by step.

First thing you need to do is copy the Email.php from system/libraries folder and place it inside your script. Then use your favorite IDE to edit these lines:

Comment out the first line which stops the direct access to the script.

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

Should look like:

<?php    //if ( ! defined('BASEPATH')) exit('No direct script access allowed');

Then goto line 1920, ie. to the _set_error_message function.
Change

function _set_error_message($msg, $val = '')
	{
		$CI =& get_instance();
		$CI->lang->load('email');

		if (FALSE === ($line = $CI->lang->line($msg)))
		{
			$this->_debug_msg[] = str_replace('%s', $val, $msg)."
";
		}
		else
		{
			$this->_debug_msg[] = str_replace('%s', $val, $line)."
";
		}
	}

to:

function _set_error_message($msg, $val = '')
	{/*
		$CI =& get_instance();
		$CI->lang->load('email');

		if (FALSE === ($line = $CI->lang->line($msg)))
		{
			$this->_debug_msg[] = str_replace('%s', $val, $msg)."
";
		}
		else
		{
			$this->_debug_msg[] = str_replace('%s', $val, $line)."
";
		}*/
	}

Now to send a mail:

<?
include('Email.php');
$config = Array(
            'protocol' => 'smtp',
            'smtp_host' => 'ssl://smtp.googlemail.com',
            'smtp_port' => 465,
            'smtp_user' => '[email protected]',
            'smtp_pass' => 'abc123',
            'mailtype'  => 'html',
            'charset'   => 'iso-8859-1'
        );
        $email = new CI_Email($config);
        $email->set_newline("\r\n");
        $email->from('[email protected]', 'My Script');
        $email->to('[email protected]');
        $email->subject('Just a test');
        $msg = "Testing CI email class";
        $email->message($msg);
        $email->send();
?>

Run the script and your mail should be sent. I also posted the exact code which should be used when sending a mail using gmail’s smtp.

Cheers!

Published
Categorized as php

Leave a comment

Your email address will not be published.