Sending email with Gmail using the CodeIgniter PHP Framework

I have just implemented this functionality for OnePage and I’d like to share it in case people find it useful.
Why send email with Gmail rather than the server’s SMTP configuration?
There are a number of advantages I see for doing this:
  • Ability to develop locally and test email sending functionality without going to lengths to setup a local mail server.
  • Ability to utilise Google Apps emails to send email from emails which are on your own domain.
  • Ability to have a reference of the mail you send using this method in the “sent” folder on your Gmail account.
Right on!
So we’ve decided that’s the route we’re going to take, so lets get going! It’s rather simple actually, especially with the fantastic CodeIgniter framework and it’sEmail Class. It should work nicely for regular PHP or with other frameworks if you just take the concepts outlined here. I must also give credit to wrs from theCodeIgniter Forums, since it is his post which I have based my solution upon.
A new config file – email.php
Place the following code inside a new config file called “email.php” and put it in your application/config directory. Config files named with the same name as a library are included automatically, and this is what we’re doing here.
  1. <?php  if ( ! defined(‘BASEPATH’)) exit(‘No direct script access allowed’);
  2. /*
  3. | ——————————————————————-
  4. | EMAIL CONFING
  5. | ——————————————————————-
  6. | Configuration of outgoing mail server.
  7. | */
  8. $config[‘protocol’]=’smtp’;
  9. $config[‘smtp_host’]=’ssl://smtp.googlemail.com’;
  10. $config[‘smtp_port’]=’465′;
  11. $config[‘smtp_timeout’]=’30’;
  12. $config[‘smtp_user’]=’your gmail email’;
  13. $config[‘smtp_pass’]=’your gmail password’;
  14. $config[‘charset’]=’utf-8′;
  15. $config[‘newline’]=”\r\n”;
  16. /* End of file email.php */
  17. /* Location: ./system/application/config/email.php */
Make sure you change ‘your gmail email’ and ‘your gmail password’ appropriately.
Sending email, now sent through Gmail
Now any emails you send using the CodeIgniter Email Class will actually be sent from your Gmail account of choice:
  1. // send an email
  2. $this->load->library(’email’);
  3. $this->email->from(‘team@myonepage.com’,’Team OnePage’);
  4. $this->email->to(“something@someaddress.com”);
  5. $this->email->subject(‘A test email from CodeIgniter using Gmail’);
  6. $this->email->message(“I can now email from CodeIgniter using Gmail as my server!”);
  7. $this->email->send();
UPDATE: It seems Posterous thinks it’s clever by turning my email’s into links, even inside code. Please adjust your code accordingly 🙂
One drawback of this method
There is one drawback of this method, which is that you cannot specify the “from” email to be anything other than your Gmail email address or an email address you have associated with the Gmail account. All email will be sent from the email account you have setup as the default in your Gmail account.

Possible error – “Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?”

If you got this error, like I did, then you need to enable SSL in your PHP config. Load up php.ini and find a line with the following:
;extension=php_openssl.dll
Simply remove the “;” and then restart Apache and you’re good to go. The “;” denotes that the line is a comment, and so removing it enables the SSL extension for Apache. Credit – http://www.boringguys.com/2007/07/20/unable-to-find-the-socket-transport-ssl-did-you-forget-to-enable-it-when-you-configured-php/
That’s all!
I hope that is useful for some people 🙂 I use it mainly for local development purposes – it’s nice to be able to test everything.
Personal notes:
Other error that you may find across:

Severity: Warning

Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Connection timed out)

Filename: libraries/Email.php

–> Possible solution is to open port 465 (You may want to consult the issue to your web hosting provider)

Code Igniter: mod rewrite

This article explains how to take away “index.php” from your CI application URLs. However, it does NOT remove the need for Index.php, which is the CI front controller i.e. even though Index.php will not appear in the URL, it still needs to be present at the top level of your site (above the /system/ directory).  To quote the User Guide,

You can easily remove this file by using a .htaccess file with some simple rules.

You need to perform the following steps to get this working:

1. Create a .htaccess file to configure the rewrite engine

2. Set $config[‘index_page’] to an empty string

3. Make sure your apache uses the mod_rewrite module

4. Make sure apache is configured to accept needed .htaccess directives

5. Restart apache and test

1. Create your .htaccess file

Create a new file named .htaccess and put it in your web directory

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#'system' can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#When your application folder isn't in the system folder
#This snippet prevents user access to the application folder
#Submitted by: Fabdrol
#Rename 'application' to your applications folder name.
RewriteCond %{REQUEST_URI} ^application.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn't true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
# Submitted by: ElliotHaughin

ErrorDocument 404 /index.php
</IfModule> 

The above configuration behaves as follows:

1. If your installation is not in the server root you will need to amend the RewriteBase line from “RewriteBase /” to “RewriteBase /folder/”

2. Checks to see if someone has entered a URL starting with “system”, all requests like this get routed to index.php, this is a security feature that removes the possibility of anyone directly accessing your system folder. You can use the same syntax to hide other folders inside your root if you want.

3. If the URL doesn’t start with “system”, the web server will check to see if there is a corresponding physical resource matching the URL, such as an image, script file, or directory.

4. If such a resource exists, that resource is returned by the webserver with no rewriting performed. If no such resource exists the url is rewritten to index.php (passed to codeigniter)

Notes for Windows users:
To create this file you must open Command Prompt and type:
copy con .htaccess [Enter]
[Press CTRL + Z]
A blank .htaccess file will be created. Now you can edit it using Notepad or your favorite text editor and copy the script above.

Note: Most Windows editors will assume that you are attempting to save an .htaccess file as a file with an extension and no filename. The Crimson Editor can be used to create and save .htaccess files and other files that have no filename.

Note: If your site is placed in subfolder specify the path in the “RewriteBase /subfolder/” line.

Note: When using the above example on some systems it may be necessary to specify the uri_protocol configuration value to achieve reliable results. (Otherwise values with periods that are passed via URI will be converted to underscores in CodeIgniter 1.7.1 eg: some.value becomes some_value)

$config['uri_protocol'] = 'QUERY_STRING'; 

2. Set $config[‘index_page’]  to an empty string

Open your

system/application/config/config.php 

and find the line that assigns $config[‘index_page’] a value, usually:

$config['index_page'] = "index.php"; 

and change it to:

$config['index_page'] = ''; 

Save the file.

3. Make sure your apache has mod_rewrite activated

This means that the apache must be configured to load the mod_rewrite module (or it might have it compiled-in). For module inclusion, usually you have to look for a line like this in httpd.conf or a file loaded by it (hint: use some quick file search utility to grep files with lines containing ‘rewrite’ string):

LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so 

If you’re running Apache2 type

a2enmod 

in the console and when prompted

rewrite 

to enable mod_rewrite.

On a Windows machine this line might look this way:

LoadModule rewrite_module modules/mod_rewrite.so 

If it is commented out (# in front), make sure to uncomment it and save the file. Checking if the corresponding module exists may be a good idea as well (but it usually does).

4. Make sure apache accepts needed .htaccess directives

This means that apache is explicitly configured to allow .htaccess files to override those directives that you use in your .htaccess file from step 1. above.

It seems to be sufficient if you add these two lines to your <Directory> section where you configure the document root for your CI application:

<Directory "/some/absolute/path/htdocs">
...
Options FollowSymLinks
AllowOverride FileInfo
...
</Directory> 

There might be other Options listed, just make sure you have FollowSymLinks as well.

Should you get a 500 Internal Server Error, try the following syntax:

<Directory "/some/absolute/path/htdocs">
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride AuthConfig FileInfo
Order allow,deny
Allow from all
</Directory> 

5. Restart apache and test your application

Works? Congratulations!

Doesn’t work? Ehrrr… well, do not give up; equip yourself with patience, double check all steps above and if it still does not work, post on the forum giving all details of your setup.

How does URL rewriting work?

<IfModule mod_rewrite.c>
...
</IfModule> 

Do what is inside only if Apache has the mod_rewrite feature (by in place compilation, or loaded module).

RewriteEngine On 

Activate the URL rewriting engine, if not already done (in main Apache configuration file.

RewriteBase / 

Define the part of the URL that won’t change nor be used for rewriting. In fact, this part will be removed before processing, and prepended after processing. This’s a good way to use subfolder-independent rewrite rules. For example, if your CodeIgniter index.php is placed in a virtual host directory, like /tests/, set RewriteBase to /tests/.

RewriteCond %{REQUEST_FILENAME} !-f 

Condition to meet for RewriteRule activation. Here, we test if the requested filename does not exist.

RewriteCond %{REQUEST_FILENAME} !-d 

Same as above, but we test for directory existence.

RewriteRule ^(.*)$ index.php/$1 [L] 

If RewriteCond conditions are met, this rule will be applied. It inserts index.php before the requested URI. The $1 represents the part of string enclosed by parentheses in left expression. The [L] means that this rule is the last one if rule is applied (thus stopping rewriting).

Configuring mod_rewrite in the httpd.conf file

The Apache mod_rewrite docs say

While URL manipulations in per-server context are really fast and efficient, per-directory rewrites are slow and inefficient…

. If you have access to your httpd.conf file, you’ll have better performance if you configure the rewrite rules in there.

You can add something like this to your httpd.conf:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]
</IfModule> 

Configuring mod_rewrite and virtual hosting with Apache 2.2

<VirtualHost *>
ServerName www.mydomain.com
DocumentRoot /path/to/ci/directory
<Directory /path/to/ci/directory>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</Directory>
</VirtualHost>