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
  • tuhin barua

    I got it working now. ignore previous post :)

  • Valentin

    Hi Jeffrey, Thank you for another great tutorial.
    I haven’t seen all the tutorials in this series and I don’t know if you use the CRUD way of programming, but I’d like to know what you think about it and if you are describing it in any tutorial.
    Also, have you any tutorial on OOP and design patterns?

    Best regards.

  • http://www.cleberoliveira.com.br Cléber Oliveira

    Hi,

    First of all, congrats for this amazing tutorial!

    About ‘\r\n’…

    We need to set this to new lines because on windows thats the “command” that says to the system to break the line!

    \r\n means: \r = return the “pointer” to the first caracter and \n = new line

    On MacOS, Linux and all Unix like, this command is just \n, but those system understand \r\n as well, so to work everywhere it’s better use \r\n !

    Sorry for this awful explanation, but I don’t know write well in english.

    I hope you understand…

  • ergo swiler

    Great tutorials hugely appreciated – thank you !

    Getting some issues from time to time :

    MAMP and my live server just didn’t like the array as you prescribed it so the email controller failed. When I rewrote the array line by line:

    $config\[\'protocol\'\] = \’smtp\’;

    for example, it worked fine.

    Created the email.php config file as suggested but now getting an “Undefined varliable: config’” error message. One for me to find a solution to next. But all this is part of the leraning curve..

    Thanks again.

    Ergo.

    • ergo swiler

      note – I used \ in the comment above thinking that brackets and inverted commas in code wouldn’t reproduce properly in the comment if I didn’t… so the code line should actually read :

      $config['protocol'] = ‘smtp’;

      which is what my code actually looked like ;-)

      Ergo.

    • Tanay

      As in the vdo when i tried to work with a email.php file in the config folder, i had the same problem but in my case the mail actually send tho it shows that “Undefined varliable: config“ error message.. even i tried with adding this file in the autoload array but i had the same error..

      regards,
      tanay

    • Phil

      I had this also, did you fix it?

    • Brad

      I got the same error, anyone find a fix? thanks

      • http://zechdc.com Zechdc

        I think I had the same error. The error I got said:

        A PHP Error was encountered
        Severity: Notice
        Message: Undefined variable: config
        Filename: controllers/email.php
        Line Number: 16

        So I looked at line 16:

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

        Removed $config, so it now looks like this:

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

        And it worked fine for me with no errors.

  • http://www.kathirvel.com Sid Vel

    You can use the constant FCPATH to get the server path to the index.php file. This has been defined in the index.php file. Avoids having to create a config variable for the server path.

    • champi

      thanks for tip :)

  • Bill

    I dont know if it was me or what. I am using wamp. When I created the email.php config file I had to change

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

    to

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

    or I would get an error about $config being undefined.

    • harpster

      Same problem here – I’m using MAMP. Thanks for the solution because I kept getting the undefined $config error notice even though the script still worked. I went back and watched the video segment several times to see if I missed something but always got that error unless I changed the code as you suggested to:

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

      • Michael

        Had same problem thanks for the solution.

    • Tanay

      Hi,
      thanks for the solution..i think it works because “$config” works as a global variable. when first run as we know first load the config folder. Since $config works as global variable so in the helper Email.php, it can easily gets the value of $config array. if u change the name of the variable in the config email.php as e.g. $config1/… u will find that it does not work at all.. and u will get bunch of errors..

      regards,
      tanay

      • Scriptaculaire

        Hi,

        I had the same problem. Thanks for the solution!

  • http://cmsblog.sk tyrhus

    Hi,
    It’s not working for me :-(.
    My browser can’t load controller (9:15 in the video).
    CODE:
    class email extends Controller
    {

    function __construct()
    {
    parent::Controller();
    }

    function index()
    {
    $config = array(
    ‘protocol’=>’smtp’,
    ‘smtp_host’=>’ssl://smtp.googlemail.com’,
    ‘smtp_port’=>’465′,
    ‘smtp_user’=>’XYZ@gmail.com’,
    ‘smtp_pass’=>’SECUREPASS’

    );
    $this->load->library(‘email’,$config);
    $this->email->set_newline(‘/r/n’);

    $this->email->from(‘nettutsTutorials@gmail.com’,'Tyrhus’);
    $this->email->to(‘miro@cmsblog.sk’);
    $this->email->subject(‘This is an email Test’);
    $this->email->message(‘Its working! Great!’);

    if ($this->email->send()) {
    echo “OK, your mail was succesfully sent.”;
    }else {
    show_error($this->email->print_debugger());
    }

    }

    }

    Any ideas?
    I’m running XAMPP on MACosx Leopard (up-to-date).

    Thank you :)

    • Tanay

      hi
      what type of error message you are getting after running the script? specify those messages..

      regards,
      tanay.

      • Thomas

        Is it possible the problem is that your class is lowercase?

  • mzz

    Dear Administer
    Please remove my email address from my previous
    Regards
    mzz

  • http://Mark Mark

    CodeIgniter From Scratch: Day 3. Sending Emails | Nettuts+ guy@gigemail.net

  • http://www.cobboc.com Amit

    Hi, In the video in the last example you kinda forgot to save the file before running it…

  • harpster

    This didn’t work for me (running MAMP). I got the ‘Your email was sent, fool’ message but no emaiI was received. I use the phpMailer class from Worx International and it’s great for html emails as well. Not sure why I’d want to switch to using the CI version of this when the phpMailer class is easier to use and I’m guessing more robust as well.

    • harpster

      Sorry my bad, I spelled protocol as “protocal” so everything works as shown in the video. I still like the phpMailer class better however as it’s similar to this CI mail class but easier to use and I trust it from using for a long time now.

  • http://www.itnewb.com/ __in

    to those getting date() error. you can fix it by editing your php config file, set your date to something like that and the error should be fix.

    [Date]
    ; Defines the default timezone used by the date functions
    ; http://php.net/date.timezone
    date.timezone = GMT

  • Yunus

    These tutorials are sooo helpful..
    I have already started grasp codeIgniter pretty well

    Thanks again for doing this

  • http://gregowen.co.uk Gstar

    This series is fantastic! I’ve learnt a shed-load already, and i’m only up to day3.
    Thanks very much Mr Way.

    I’ve got the email system working, no errors, but it always sends 2 emails out.
    I can’t for the life of me figure it out.
    Has anyone else had this issue?

    Thanks again.

    • http://www.maccast.com Adam Christianson

      I’m also getting two emails. I think one may be a BCC sent by default to my gmail account.

      • http://www.webwithschilly.com Patrick

        I am also getting this… Anyone get this fixed?

  • Eoghan

    Thanks Jeffrey, you explain things very well.

  • Maximus

    Fantastic tutorials on CodeIgniter! Thank you very much, Jeffrey, for all of the time that you put into this series.

  • AJ

    thanks! Awesome!

  • Franklin

    Hi the tutorials are exellent but i have and error, this is the error” 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

    so if you can tell me it would be great

    • Franklin

      friends i found the error, when you have this kind of error you should go to the php.ini in the “dynamic extensions” adn find the extension:openssl.dll and uncomment it because when i found it, it was like this ;extension:openssl.dll so i erased the “;” then i restarted the web server services and it worked.

  • Shahin

    HI anybody get this warning?

    A PHP Error was encountered

    Severity: Warning

    Message: date() [function.date]: It is not safe to rely on the system’s timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected ‘America/Los_Angeles’ for ‘PDT/-7.0/DST’ instead

    Filename: libraries/Email.php

    Line Number: 662

  • http://www.code.my devlim

    i notice that after u put the config array in the email.php in the config folder, u didnt delete the $config in the $this->load->library(‘email’, $config); and u didnt save the email.php controller before u perform final test~

  • Larry

    Just a quick tip.. good practice would mean you do next:
    $file = $path . DIRECTORY_SEPARATOR . ‘ci’ . DIRECTORY_SEPARATOR . ‘folder’ . DIRECTORY_SEPARATOR . ‘info.html’;

    Because the directory separator is different on *win boxes. =P

  • maramot

    I keep getting an error message:

    Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.google.com:443 (A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. )

    I am using XAMPP 1.7.3 which has no php_openssl.dll in the xampp/php/ext dir but it is in some way built-in. When I run phpinfo(), the following is shown in the “apache2handler” section:

    mod_ssl/2.2.14 OpenSSL/0.9.8l

    In the “Apache environment” section of the phpinfo() page I have a variable “OPENSSL_CONF” with a value of “C:/xampp/apache/bin/openssl.cnf” In the same page I have a separate openssl section where “OpenSSL support” is listed as “enabled”.

    In the “Welcome” page of my xampp configuration panel I have the following notice:
    For OpenSSL support please use the test certificate with https://127.0.0.1 or https://localhost
    I have used this and accepted the unverified certificate permanently, just in case non-acceptance is the source of the error.

    In the “Security” page of my xampp configuration panel, the following ports are listed:

    The XAMPP default ports:

    ftp 21/tcp # File Transfer [Control] (XAMPP: FTP Default Port)
    smtp 25/tcp mail # Simple Mail Transfer (XAMPP: SMTP Default Port)
    http 80/tcp # World Wide Web HTTP (XAMPP: Apache Default Port)
    pop3 110/tcp # Post Office Protocol – Version 3 (XAMPP: POP3 Default Port)
    imap 143/tcp # Internet Message Access Protocol (XAMPP: IMAP Default Port)
    https 443/tcp # http protocol over TLS/SSL (XAMPP: Apache SSL Port)
    mysql 3306/tcp # MySQL (XAMPP: MySQL Default Port)
    AJP/1.3 8009 # AJP/1.3 (XAMPP: Tomcat AJP/1.3 Port)
    http-alt 8080/tcp # HTTP Alternate (see port 80) (XAMPP: Tomcat Default Port)

    I am following the tutorial by using the mentioned port. Still getting the error mentioned in the beginning.
    I am running the xampp server on a windows XP SP3. Anti-virus software is disabled, skype is offline… :) I am out of ideas. Please suggest possible causes for this error.

    • mark

      please tell me you got this working I have the exact same problem on almost the same set-up can’t get it working

  • http://www.charlesbryant.co.uk Charles

    What an awesome tutorial. FACT. Tried using Zend framework before it was good but learning was slow going, this is just stupidly easy. Codeigniter is much more leight weight than Zend I imagine it does not have as many features, but what a great starting point to get into MVC, and these video tutorials are just so easy to follow. Best tutorial on PHP I have ever followed.

  • Chris

    Someone may have already commented on this, but I didn’t see…

    After config/email.php is set up, then on line 13 of controllers/email.php

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

    you can remove $config, thus:

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

    Leaving it $config as seen in the tutorial throws an undefined variable error for $config on my system. (The controller, as set up in the tutorial, sends the email with the attachment, even with the error code.) I suspect the the $config array is already called by the email library, so calling it again looks like a local variable call. If someone knows better, please share.

    I hope this helps someone.

  • warren husay

    very, very, very nice tutorial

    I love you Jeffrey Way!
    will you marry me. LOL :)

    By the way how do i download the videos?

    thanks

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Ummm…. :)

      If you search for CodeIgniter from Scratch on Blip.tv, you should be able to find a download link on the video page.

  • Arian

    excellent tutorial.

    thank you

  • dj

    Thank you so much for making this codeigniter series. I am really enjoying it a lot!

  • Petar

    I have a problem, when i receive the email, i just get the subject, no body, no attached file. Can someone help me, or telling me what need i do to fix the problem.

    Thanks

  • http://www.guilhermemiari.com.br Guilherme Miari

    Jeffrey, congratulations for tutorial, the code working, but is necessary a little ajust for conect with gmail.

  • Faiyaz

    If Any one having a problem regarding SSl
    1. Stop the Apache service
    2. Copy libeay32.dll and ssleay32.dll from your ..wamp/php folder and past it to your ..wamp/apache/bin folder, overwriting the older files there
    3. Edit the ..wamp/apache/bin/php.ini and uncomment the “;extension=php_openssl.dll” (remove the semicolon at the start of the line)
    4. Start the Apache service.

    Thanks a million Jeff.You made my day…

  • http://www.jordanarsenault.com Jordan Arsenault

    SOLID tutorials.
    Keep it up Jeff.

  • Robert

    The CI tutorials have been great as we have begun using CI for development of smaller projects. There’s two things we’d like to see:

    1) Currently we use custom code utilizing the PEAR Mailer to send mime emails that include both an HTML and a text version of each email. We’d love to see if CI can do this as well, especially if there is an internal class that is able to simply take the HTML version and strip out the HTML tags and replacing those that can be such as a \r\n for a <br /> or a \r\n\r\n for a </p>. Having to only enter the one version would make like so much easier. If any of this is possible, a quick vid tut would be great!

    2) I really wish nettuts would also show subsequent tuts in the series on any given page. We see the previous in the “Catch Up” area, but it would be great if nettuts kept track of one that follow as well and appended a “Follow Up” area immediately after the video box, allowing us to quickly continue on with the series.

    Thanks!

  • siryu88

    $config = Array(
    ‘protocol’ => ‘smtp’,
    ‘smtp_host’ => ‘ssl://smtp.mail.yahoo.co.id’,
    ‘smtp_port’ => ’465′,
    ‘smtp_user’ => ‘blablabla@yahoo.co.id’,
    ‘smtp_pass’ => ‘blablabla’,
    ‘mailtype’ => ‘html’,
    ‘charset’ => ‘iso-8859-1′,
    ‘wordwrap’ => true,
    ‘crlf’ => ‘\r\n’
    );

    what’s wrong with my config?? I Can’t send any email when mailtype is html. But, when I set it to text, email sent to my email.

    I want to send a link to activate user ID, so I think, I have to use html type right??

    This is my html in verification_mail.php :

    TEST

    Please Copy and Paste the link below to activate your ID at blablabla.com .

    any Idea??

    • http://www.koyo-t.net Koyo-T

      Hi siryu88,

      your html template must be in double quotes

  • jhanson

    Seriously really nice tutorials Jeff. I am officially a fan! Where can I get some more of your programming tutorials?

  • indigoblue

    hi everyone…
    first, I just wanna say this is a great tutorial. but I’ve some trouble when tried to send an email, like at this tutorial.
    When i try to refresh http://localhost/ci_day3/index.php/email/index, there are not error report, but it’s take a long time response… :( and nothing was sent..
    I used appserv as my webserver, and WIN 7..
    This is my code :

    ‘smtp’,
    ‘smtp_host’ => ‘ssl://smtp.googlemail.com’,
    ‘smtp_port’ => 465,
    ‘smtp_user’ => ‘mymail@gmail.com’,
    ‘smtp_pass’ => ‘mypass’
    );

    $this->load->library(‘email’,$config);
    $this->email->set_newline(‘\r\n’);

    $this->email->from(‘mymail@gmail.com’,'myname’);
    $this->email->to(‘mymail@gmail.com’);
    $this->email->subject(‘This Is Email Test Bro’);
    $this->email->message(‘Test’);

    if($this->email->send()){
    echo ‘Your Email Successfull Cuy..’;
    }
    else{
    show_error($this->email->debugger);
    }
    }
    }
    ?>

    I’m sorry if my english is so poor. hope you understand what I mean..
    regard…

    • indigoblue

      haha, i’m sorry… now, i get the answer from previous answer…. thx

  • Denis

    What an excellent series!

    I’m new to MVC and CodeIgniter and thought the learning curve would be dauntingly steep. Not so with Jeffrey Way’s relaxed and accessible delivery. Kudos to him!

    A general question about tutsplus.com:

    I have an slow connection (actually high-latency – I’m on the wrong side of the planet, sorry) and need to pause the playback for up to an hour so that it plays back uninterrupted. I don’t mind doing that, but I often want to return to an earlier screencast and am irked at having to go through the process again! Is it possible (and legal) to download the screencast videos? Is this feature available to Premuim members? Can anyone help with other tips to improve my viewing experience?

    Thanks in advance.

  • Jonas

    I never really thought much of MVC, but since I started watching these screencasts, I’m getting more and more into it.
    codeIgnite seems like a good way to focus on what one really wanna create, instead on focusing on all the things under the hood.

    Very nice screencasts!
    kudos!

    Jonas

  • Cam

    Just a note on newline characters, if sending a long text email with the \r\n for new lines, make sure you enclose the text in double quotes not single quotes.

    For example

    $emailbody = ‘Line 1 here\r\n’;
    $emailbody = ‘Line 2 here\r\n’;

    etc. will produce
    Line 1 here rnLine2 here rn
    in your email, whereas

    $emailbody = “Line 1 here\r\n”;
    $emailbody = “Line 2 here\r\n”;

    should produce:
    Line 1 here
    Line 2 here

    Hope this helps someone. Had me stuck for a while.

  • http://vivekipedia.tumblr.com/ kaizer1v

    Hey Jeff,

    I see you were about to handle errors and just didn’t in this as well as the previous. Does php handle exceptions like throwable ones or try {} catch {} instead of the if else statement you used here? (09:45 through 09:46)?? If php does, it would be great to see it being implemented. Just a suggestion.

  • Anthony

    Ok. Earlier today I posted a problem about sending emails as per Day 3 CI video that Jeffrey Way had done. I found my answer!!! After getting home (away from the firewall at work), I found the following link (it was much help!!). http://www.apachefriends.org/f/viewtopic.php?t=20981

    respectfully,
    Anthony

  • http://www.jasongroulx.com Jason

    Hi Jeff

    I was wondering how you are able to send emails from your localhost using MAMP … I spent some time looking into it because my email wouldn’t send but when I tested it online it would work .. if anyone could help me out with this one it would be greatly appreciated

    Great tutorial, this is really a great series!

  • http://www.asktechtz.com Aaron

    Great tutorial,thanks a lot..

  • Santosh

    Awesome Jeff!

    I registered as a premium member of week 1 of visiting your blog. Great job and thank you for all the education! It’s been fun!!

  • ahmadtamimi

    Greeeeeeeeeeeeeeeeat Tuts :)

  • Intercalls

    Great tutorial. Everything works fine. Thanks to the comments for $config variable which was giving error.
    Thanks Jeffery and others.
    Awesome
    Cheers
    Pete

  • Brad T

    I’m new to PHP and Codeigniter (by the way great series Jeffrey) any suggestion would be greatly appreciated.

    I’m getting this error when sending an email. I’ve followed this tutorial at less 3 time and can’t find a solution. I seen several other having the same error, but no solution was posted.

    A PHP Error was encountered

    Severity: Warning

    Message: mail() [function.mail]: Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set()

    Filename: libraries/Email.php

    Line Number: 1519

  • Wolfgang

    Hi,
    first of all thanx for the Tutorial about CI!!!
    one Problem i had was that when i put the Email config Array in the /config/email.php i get the error:
    Severity: Notice

    Message: Undefined variable: config

    Filename: controllers/email.php

    Line Number: 12
    But the email where sent?!?
    Any Idea about it?

  • http://www.terracoding.com Rob White

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

    Should read

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

    As you’re no longer explicitly defining $config in that file any more.

  • Chris E

    I understand that Controller is now CI_Controller in the latest CI release, but now it this error:

    Fatal error: Call to undefined method CI_Controller::CI_Controller() in MY_DIR/ci/application/controllers/email.php on line 8

    which is:

    class Email extends CI_Controller {
    function __construct() {
    parent::CI_Controller();
    }

    Any ideas?

    • Chris

      Apparently it’s now:

      class Email extends CI_Controller {
      function __construct() {
      parent::__construct();
      }

  • Fahmy

    Hi, I have also same problem like this

    Fatal error: Call to undefined method CI_Controller::CI_Controller() in MY_DIR/ci/application/controllers/email.php on line 10

    Pls help me solve it.

    Any way, very very thanks for your great tutorial.