CodeIgniter From Scratch: Day 3
videos

CodeIgniter From Scratch: Day 3. Sending Emails

This entry is part 3 of 17 in the CodeIgniter From Scratch Session
« PreviousNext »

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


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://dagrevis.lv/ daGrevis

    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;

  • http://dagrevis.lv/ daGrevis

    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

    • http://dagrevis.lv/ daGrevis

      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.=]

  • Hernan

    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!

  • http://www.freetutorialsrock.com qlidnaque

    thanks, I’m just getting started on learning a framework (Codeigniter) and your tutorials are helping me soo much! thanks!

  • Raymond

    Thanks man! I’m learning a lot from you!

  • http://www.redfishbluefishdesign.com jeff

    It says the file has been deleted. And it’s a shame too because I had to watch the worst commercial this time! Arg!

    • http://www.redfishbluefishdesign.com Jeff

      Came back a few hours later and it was there. Thanks if you did anything! (Or perhaps it was an error over at Vimeo).

  • http://brystedesign.com Bryan

    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

  • http://www.matthewcnorton.com Matthew

    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!

  • http://www.matthewcnorton.com Matthew

    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.

    • Chris

      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!

      • Chris Li

        Oops, sorry, this is the correct one:

        $this->load->library(‘email’, $this->config);

        Hope that helps!

  • http://www.cambur.es frank

    Jeffrey rocks!
    best tuts ever!

  • ido

    only at day 4 but this is great :) tnx
    will it show in future days how to connect with css and JS?

  • http://www.tugux.com SUnny

    Great tuts

  • Jack

    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());
    }
    }
    }

  • Jack
  • Jack

    Now I am getting this http://pastebin.com/uCGYTzXF
    You can delete previous comments, sorry for mess.

  • Jack

    Please remove all my comments. I was relying on free hosting with bad configuration. On localhost it works perfect.

    • http://powerw33t.com Juni

      Jack, how did you solve the problem?

      • Jack

        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.

    • http://powerw33t.com Juni

      Thanks dude …now im on it!

  • bamboshu

    in CI 2.0.1 you must delete __construct() function from controllers/email.php to send email :)

    • Aaron

      THANK YOU for point that out. I was sitting here scratching my head until I head your post. THANKS!!

    • http://www.rcdmk.com Rcdmk

      Actually, you have to rename the “parent::Controler()” to “parent::__construct()”

  • http://www.directv.com Al

    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??

    • Chris Li

      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);

      • Salvador

        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

  • http://www.girisoft.net Viruthagiri

    Nice tutorial :) . Thanks

  • Dennis

    Great tutorials…thanks for creating them :)

  • Tif

    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.

  • Danny

    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());
    }
    }

    }

    • http://www.stasikowski.com Lech

      exactly, thx!!!

    • Chris Li

      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;
      }
      }
      ?>

  • frank

    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

    • Salvador

      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

      • BG

        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

      • Jake D.

        This fixed the problem for me. Thanks for the solution.

  • frank

    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

    • Dieter

      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

    • Chris Li

      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.

    • Brett

      Frank, did you ever get this resolved?

  • abc

    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….

  • techguy

    great tutorials

  • rohan

    good one

  • http://www.callumrexter.com Callum

    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

  • http://antonvrg.tk/ Anton

    Great Job! these tutorials are great. Love em!

  • stage

    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

    • Itay

      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

  • http://www.wanderasinc.com Mayowa

    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.

    • BRen

      If you are using WAMP Server then make sure the openssl extension is enabled.

  • Newlex

    Hey Jeffrey,

    great series here ! I’m beginning to go deeper and deeper into PHP and this CodeIgniter series is just perfect. Thank you !

  • Mike E

    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.

  • Lucia

    Perfect tutorials. Keep up with the good work!

  • Tom

    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

  • Arsalan

    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.. :-)

  • Jonathan

    Pleas continued the great job to teach us the great tool that is codeIgniter !!!

    Thks a LOT!!!! Man THKS! THKS!

  • http://faridlab.com farid hidayat

    Thanks Jeff, it’s Usefull

  • http://www.scaleit.co.za Eugene Koekemoer

    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)

  • Hakan

    Gmail tags spam if i add file :)

  • http://www.scaleit.co.za Eugene Koekemoer

    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] =>
    )
    )

  • Brett

    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?

    • Ian

      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.

  • http://www.megadutch.com John M. Denooyer

    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.

    • Brett

      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?

      • http://www.megadutch.com John M. Denooyer

        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.

    • Ian

      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

  • Ian

    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! :-)

  • http://mjphelps.x10.mx Michael Phelps

    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.

    • http://mjphelps.x10.mx Michael Phelps

      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?

  • gabi

    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.

  • http://sraji.wordpress.com/ rajee

    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

  • http://www.dimension-internet.com Sven

    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.

  • http://www.soleguia.com Soleguia

    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!

  • Robo

    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.