At the request of some of our readers, this week, we’ll examine just how easy it is to send emails with attachments using Gmail. With raw PHP, this would be a long and tedious task. However, with CodeIgniter, it’s a cinch! I’ll show you how in this eighteen minute video tutorial.
Catch Up
Day 3
- Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for more daily web development tuts and articles.


Thanks again! xD This works perfectly with two conditions…
1) CI 1.7.x not 2.x, for example,
2) php_openssl.dll must be enabled;
By the way, I think all that stuff should go into model not controller.
And yea… What’s the difference? I can’t see… xDD 30 secs waste of life. =]]
$foo = array(
‘a’ = 1,
‘b’ = 2,
‘c’ = 3
);
$foo['a'] = 1;
$foo['b'] = 2;
$foo['c'] = 3;</pre
Didn’t realize that $configuration that’s setted in email.php isn’t all array. So if just $c = array() would redeclare previous array – delete values setted in it before. My bad.=]
Ok these are probably the bests tutorials I’ve ever seen. Thank you very much from Argentina, Im starting a project using CI and this was my salvation :)
Keep it up!
thanks, I’m just getting started on learning a framework (Codeigniter) and your tutorials are helping me soo much! thanks!
Thanks man! I’m learning a lot from you!
It says the file has been deleted. And it’s a shame too because I had to watch the worst commercial this time! Arg!
Came back a few hours later and it was there. Thanks if you did anything! (Or perhaps it was an error over at Vimeo).
When I send my attachments, they seem to send blank documents. I open up the .txt file from my email client and its empty inside. On the server, it has text inside. I tried an image instead of text and it just send my a broken image. Any ideas on why?
I used the following file path:
$file = FCPATH.’attachments/newsletter1.txt’;
I know its not the same way he did it in the tutorial, but it should still work… At least I think it should
Jeffrey Way I really appreciate the time it took you to make these tutorials. Your teaching style is very clear and transparent. I really like that you can remember some of the confusing terminology when you are first starting off and explain it in a way newbies can understand.
Thanks again from Canada!
Hi Jeff,
Great tutorial, not sure if you are still answering questions, if you are or if someone in the community can help..
Just wondering where you are loading in the $config array values for Gmail. You have moved the values to the config folder and it looks like you are not calling them back in?
Even when you load it:
$this->load->library(‘email’);
There is no call to the array values?
It seems as though without the values you can not send email properly.
If anyone has an answer to this please respond.
Thanks.
Hi,
You still need to reference the config file, although you need to make a slight change to reference the config settings correctly when they are autoloaded:
$this->load->library(‘email’);
Hope that helps!
Oops, sorry, this is the correct one:
$this->load->library(‘email’, $this->config);
Hope that helps!
Jeffrey rocks!
best tuts ever!
only at day 4 but this is great :) tnx
will it show in future days how to connect with css and JS?
Great tuts
I am getting this error:
“An Error Was Encountered
Unable to load the requested class: email”
source:
‘smtp’,
‘smtp_host’ => “ssl://smtp.googlemail.com”,
‘smtp_port’ => 465,
‘smtp_user’ => ‘xxx’,
‘smtp_pass’ => ‘zzz’
);
$this->load->library(‘email’, $config);
$this->email->set_newline(“\r\n”);
$this->email->from(‘xxx@gmail.com’, ‘Jack’);
$this->email->to(‘yyy@gmail.com’);
$this->email->subject(‘This is an email test’);
$this->email->message(‘It is working. Great!’);
if($this->email->send())
{
echo ‘Your email was sent, fool.’;
}
else
{
show_error($this->email->print_debugger());
}
}
}
Here is full code http://pastebin.com/TSSs6jY2
Now I am getting this http://pastebin.com/uCGYTzXF
You can delete previous comments, sorry for mess.
Please remove all my comments. I was relying on free hosting with bad configuration. On localhost it works perfect.
Jack, how did you solve the problem?
I installed apache/php/mysql on my own computer. Earlier I was too lazy to do this so I was using web hosting service which provided some limits.
Thanks dude …now im on it!
in CI 2.0.1 you must delete __construct() function from controllers/email.php to send email :)
THANK YOU for point that out. I was sitting here scratching my head until I head your post. THANKS!!
Actually, you have to rename the “parent::Controler()” to “parent::__construct()”
Using CI 2.0.1, I am able to send email with attachment. However, I get a PHP error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: config
Filename: controllers/email.php
Line Number: 24
The line number 24 points to this line of code in my controller code:
$this->load->library(‘email’, $config);
Any idea what’s wrong??
When the config file was moved out for autoloading, the reference to $config is lost, since the array isn’t there anymore. You will need to make a reference to the config file like so:
$this->load->library(‘email’, $this->config);
Actually, with the new version of CI you don’t even need to reference $this->config anymore. If the reference is missing it’ll auto-load from config/email.php
Cheers
Nice tutorial :) . Thanks
Great tutorials…thanks for creating them :)
AI, I had the same error. I tried removing the $config variable from that line but still had an error so instead I went into library > email.php and added the host, user and pass and port variables there and it now works.
But certainly you need to remove the $config from that line.
It is very easy to get it to use for CI 2.0.x, wich is also available on the CI website as a Class.
Just remove the:
function __construct() {
parent::Controller();
}
Stop making an array, just give them the information. Code should be like this:
class Email extends CI_Controller {
function index() {
$config['protocol'] = ‘smtp’;
$config['smtp_host'] = ‘ssl://smtp.googlemail.com’;
$config['smtp_port'] = 465;
$config['smtp_user'] = ‘youremail@gmail.com’;
$config['smtp_pass'] = ‘passwordhere’;
$this->load->library(‘email’);
$this->email->set_newline(“/r/n”);
$this->email->from(‘your@gmail.com’, ‘from name’);
$this->email->to(‘to@email.com’);
$this->email->subject(‘email van CI’);
$this->email->message(‘look this is working’);
if($this->email->send()) {
echo ‘Your email was sent, fool’;
}
else {
show_error($this->email->print_debugger());
}
}
}
exactly, thx!!!
I’m not exactly sure why the __construct() was included for this tutorial, BUT, its worth noting that in CI 2.0.2 documentation (http://codeigniter.com/user_guide/general/controllers.html), if you decide to use the __construct to load whatever you need to load when the class gets called, you will need to do it like so, for example (note the example is for CI 2.0.2, which has slight changes to tutorial):
some_string = ‘hello world’;
}
public function getString() {
return $this->some_string;
}
}
?>
Hey jeff it’s a good tutorial , but i am facing a problem while sending emails .I am getting a error
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)
I know there might be some problem with my smtp settings becuase i am on localhost..is there any way to fix that ….
Please help me out
Hello, i had the same problem. I am running a WAMP server localy, what you need to do is edit
your httpd.conf file and REMOVE the hash from this line:
“#LoadModule ssl_module modules/mod_ssl.so”
becomes
“LoadModule ssl_module modules/mod_ssl.so”
Hope this helps
I tried this, but the httpd.conf file is already configured as suggested, without the hash. Any other suggestions to resolve the error associated with the following message?
A PHP Error was encountered
Severity: Warning
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.gogglemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)
Filename: libraries/Email.php
Line Number: 1673
Hey jeff it’s a good tutorial , but i am facing a problem while sending emails .I am getting a error
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)
I know there might be some problem with my smtp settings becuase i am on localhost..is there any way to fix that ….
Please help me out
I’ve got the same error as you had Frank. Did you already found a solution on this. I’m also working on my localhost, but couldn’t find the error yet.
Can somebody help me (/us) with this issue?
thx
Dieter
Yeah, i had the same issue here. You basically don’t have an extension loaded in your php configuration. If your using a WAMP stack (i’m using XAMPP), then you can just go into your php.ini file, find the follow line, and uncomment (or if you don’t have it at all, just simply add the extension in) it like so:
;extension=php_openssl.dll
TO
extension=php_openssl.dll
NOTE: if it still doesn’t work, then you may not have the php_openssl.dll in the ext folder. In that case, maybe this can help: http://blog.boringguys.com/2007/07/unable-to-find-socket-transport-did-you.html
If you don’t know where your php.ini file is located, I usually create a phpinfo.php file and put it in the root of your site, the contents of phpinfo.php is basically:
<?php
phpinfo();
There you should see the location of your php.ini.
Frank, did you ever get this resolved?
Could someone give a brief explanation about the un-required $config, which causes an issue when included but which works when excluded.
thanks – I’m sure more than I will benefit….
great tutorials
good one
Have been following these fantastic tuts but using 2.0.2 and just adapting each as I go using the fantastic codeigniter user guide, the email one gave me some difficulty until i realized you can use:
$this->email->initialize($config);
to set the config information rather that pass it as a parameter of $this->load->library(‘email’);
Alternatively set it in your config/email.php file
Great Job! these tutorials are great. Love em!
I get an error at line: parent::Controller();
Fatal error: Call to undefined method CI_Controller::Controller() in C:\wamp\www\ci_day3\application\controllers\email.php on line 10
Hi,
happend to me also but looking in codeigniter documentation i found the solution
use this syntax instead:
class email extends CI_Controller {
function __construct() {
parent::__construct();
}
hope its still usefull
I’m getting a lot of errors. Pretty sure I’ve tried every suggestion here, deleted the parent function, removed the array, updated my php ini file, no luck.
This is the first of 13 errors I’m getting.
A PHP Error was encountered
Severity: Warning
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)
Filename: libraries/Email.php
Line Number: 1673
Someone please help.
If you are using WAMP Server then make sure the openssl extension is enabled.
Hey Jeffrey,
great series here ! I’m beginning to go deeper and deeper into PHP and this CodeIgniter series is just perfect. Thank you !
I have a theory on why set_newline is required, not sure if it’s right.
in the various major OSes (i.e. Win, OSX, GNU/Linux) you have slightly different newline return characters. In OSX and GNU/Linux you need both /r and /n to get a newline (/r being carrage return old fashion like, and /n creates the actual new line) in Windows however one only needs /n since it auto includes the /r.
WHY it’s required is because the headers need it to space itself. Not sure if the theory is right, I don’t normally work with E-mails (yet, but this tut did help make me realise that I can easily)
Just a thought.
Perfect tutorials. Keep up with the good work!
Please help I cannot get this working, the page gets stuck loading.
I am using version 2.0.3
Here is my code for the email.php config file:
Here is my code for the email.php controller:
load->library(‘email’);
$this->email->set_newline(‘\r\n’);
$this->email->from(‘your@gmail.com’, ‘from name’);
$this->email->to(‘t.peet1988@gmail.com’);
$this->email->subject(‘email van CI’);
$this->email->message(‘look this is working’);
if($this->email->send()) {
echo ‘Your email was sent, fool’;
}
else {
show_error($this->email->print_debugger());
}
}
}
?>
Thanks
Really Awesome.. Jeffery man you rock.. Im a php developer, i wanna learn CI, and your videos are really helping me.. if you could add more videos regarding CI ajax and jquery that would be awesome.. Looking forward for more videos.. :-)
Pleas continued the great job to teach us the great tool that is codeIgniter !!!
Thks a LOT!!!! Man THKS! THKS!
Thanks Jeff, it’s Usefull
Awesome tutorial, thanx!
I know it’s a wee bit outdated, but this will help everyone using both older and newer versions of CI.
Here’s a tip to eliminate having to do the foreach loop check every time you call data from a db:
Add this function to the system Model page:
Location: ./system/core/Model.php
function db_data($q)
{
if($q->num_rows()>0) {
foreach($q->result() as $r) {
$data[] = $r;
}
return $data;
}
}
Then, whenever you do a db callback, merely do this:
function getIndexData()
{
return db_data($this->db->get(‘test’));
}
function getSomeOtherData()
{
return db_data($this->db->get(‘test’));
}
The function db_data will be globally available for ALL projects, because it’s in the system Model file.
(I just started learning CI yesterday, so someone else might have a better implementation method for the db_data function)
Gmail tags spam if i add file :)
Here’s another nifty hack to convert all the stdClass objects to clean arrays:
Again I’m implementing this in the Model.php page
Location: ./system/core/Model.php
By default, the class will provide you with an object array like this:
Array (
[0] => stdClass Object
(
[detailID] => 1
[rentalDetailsID] => 1
[detailType] => Bedrooms
[detailValue] => 2
[detailDescription] =>
)
)
To clean this up to a standard array, add this to the Model page:
function obar($object)
{
foreach($object as $k => $v) {
if(is_object($v))
$arr[$k] = obar($v);
else
$arr[$k] = $v;
}
return $arr;
}
and call it with:
$arr = obar($this->your_model->yourModelFunction());
This will now output:
Array
(
[0] => Array
(
[detailID] => 1
[rentalDetailsID] => 1
[detailType] => Bedrooms
[detailValue] => 2
[detailDescription] =>
)
)
I’m running XAMPP for Windows, but am getting this PHP error:
Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)”
It references “Filename: libraries/Email.php”. Any ideas on how to fix?
Bret,
This is an old post from 2008 but it might still be true. It says ssl is not supported in xamp.
http://www.projectpier.org/node/817
The mail function settings they show in the php.ini file are like the ones in my php.ini file but I am running full PHP on an IIS server.
Hopefully that’s the issue and their method will fix your issue.
I’ve been knocking my head out trying to figure out why I was getting errors when I copy the code correctly.
I finally wrote to my ISP, Bluehost.com, and apparently they closed off Port 465 . Here is their reply:
Dear Customer,
I’m aware that you are using port 465, but you won’t ever be able to connect via any smtp ports to external networks. In other words, you can’t connect to gmail ever from our servers via smtp. You can certainly send to gmail, but you can’t connect via smtp to gmail.
So, I’m going to skip the Day 3 tutorial.
John,
I’m having a similar error but on WAMPP. I’ve posted my issue above, but still don’t have a resolution, so I think I’m going to skip Day Three as well.
Brett
PS. Is there a way to subscribe to this so that we get emailed when someone posts?
I don’t know about receiving replies, Brett. I’m new to this forum.
I’ve just been checking Day 3 every now and then.
John,
I think Jefferey mentions it in the video but there is also port 587 for gmail
http://mail.google.com/support/bin/answer.py?answer=78799
Hopefully bluehost isn’t blocking that one too
Hi,
Thanks for the awesome tutorials Jeffery Way!
I recommend your tutorials and the value of the Premium Content subscription to friends all the time. Even though most of what I need is free content, I feel good about paying the subscription just to give something back for the free ones.
I know this is old and it might be mentioned already in some of the comments (I didn’t read through over 300 of them) but for anyone else late in the game like me,
extending classes begin with “CI_” now so “class Email extends Controller” is now
“class Email extends CI_Controller”
Also they have updated to the object oriented method so in the Email construct
“parent::CI_Controller” changes to, “parent::__construct”
Changes like this can be seen by looking in the core directory
Those minor changes and this tutorial still works great! :-)
I was going over some of the documentation and CI forums, and discovered that in 2.0.x, you don’t need the construct function for this.. If you DO add it, just parent it to itself:
function construct()
{
parent::__cnstruct();
}
I keep forgetting these tuts are for an older version of CI.. The functionality is there, but the methods have changed slightly.
And if I had read ALL the comments, I would see that someone already brought that to light.. Can I blame the fact it’s 1am here?
The config for gmail is not working.
I was getting this error: ” fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (Unable to find the socket transport “ssl” – did you forget to enable it when you configured PHP?)”
After I’ve changed the config with another email account (not gmail account) it worked perfectly.
Hai,
I followed your tutorial to send mail to gmail account, but i ended up with the following error,
Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.
I don’t know how to solve it.
I have been googling to find a solution for this, but didn’t make it
Also, i didn’t find a line extension=php_openssl.dll in php.ini file
Help me.
I am running on Fedora 14
I’ve changed the code like this :
class Email extends CI_Controller
{
function __construct()
{
parent::__construct();
}
function index()
{
$this->load->library(‘email’, $this->config);
$this->email->set_newline(“\r\n”);
so CI, construct and $this->config
and it works.
Hi!
I’ve been trying the last step: “create the email.php file and put it into the config directory”,
but it doesn’t work, returns me:
The following SMTP error was encountered:
Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.
Until there it works fine, but when I create that file and set the parameters it crashes.
I’m working with CI 2, ¿maybe some different way or anything?
Thanks for your help and for tutorials, they’re really great!
Great tutorial again.. The only thing that threw me off a bit was when I moved the $config array to be in its own file in the config directory. This was because I got an error saying that $config was undefined.
If anyone else has this problem simply remove the $config variable from:
$this->load->library(‘email’);
Thanks again.