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://brainstormsolutions.co.uk Sat

    Awesome Tutorials dude… Thanks a lot… I am learning real codeIgniter from your tutorials.. Plz keep going….

  • Mr Chub

    Great
    But i have a error:
    Call to undefined method CI_Controller::controller() in C:\wamp\www\ci\application\controllers\email.php on line 10
    Here is my code:
    class Email extends Ci_Controller{

    function __construct()
    {
    parent:: controller();
    }
    function index()
    {
    $config = Array(

    ‘protocol’=>’smtp’,
    ‘smtp_host’=>’ssl://smtp.googlemail.com’,
    ‘smtp_port’=>465,
    ‘smtp_user’=>’myemail’,
    ‘smtp_pass’=>’mypass’

    );

    /*forbinder til libary */
    $this->load->libary(‘email’, $config);
    $this->email->set_newline(“\r\n”);

    /*afsenderen*/
    $this->email->from(‘nettutsTutorials@gmail.com’);
    /*modtageren*/
    $this->email->to(‘renefrisker@gmail.com’);
    $this->email->subject(‘Det er en email test’);
    $this->email->messange(‘Det virke sku’);

    if($this->email->send()){
    echo’Din mail bliv sent’;
    }

    else
    {
    show_error($this->email->print_debugger());
    }
    }
    }

    • Peter Häggstrand

      @mrChub: Look at the previous comment page, you will find the answer there. It has to do with the version nr of CodeIgniter. This tutorial is based on 1.7, you’re propably using 2.1.

    • Pablo Vera H.

      In construct function is: parent::__construct();
      This is for Codeigniter 2.0.

      • Matt

        I was getting the same error. I came here after already changing my code to your solution, but I’m now getting a 504 error.

        Gateway Time-out

        The gateway did not receive a timely response from the upstream server or application.

        Any thoughts?

  • Rene

    i have a error:

    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: 1553

    can any one help

    • http://www.dragoviandesign.be Peter Vermeulen

      Hey,

      The problem doesn’t lie with codeigniter. It’s your apache server that has some problems doing the requested operation. The first thing i’d do is to make sure that you have an updated server ( php 5.0+ at least ), secondly take a look at the php.ini file ( which should be located in your xampp folder under php ).

      Do a search for the keyword “mail” and you’ll find a block like this :

      [mail function]
      ; For Win32 only.
      ; http://php.net/smtp
      SMTP = localhost
      ; http://php.net/smtp-port
      smtp_port = 25

      make sure that this block is uncommented and your SMTP is set to localhost :)

      hope this helps !

    • http://www.dragoviandesign.be Peter Vermeulen

      You could also try setting up mercury for xampp and configuring it. In some countries your service provider blocks all outgoing traffic on ports under 1024 ( this is the case in my country ).

  • Dale

    Fantastic series, thanks for making these.

  • mehmet demir

    I am writing exactly the same code but I’m getting error like “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?)” if I get rid of the ssl part it didn’t work again

  • Roy

    Nice Tutorial

  • Rexx

    Man just keep up with good work! Your tutorials really helps, thank you so much!

  • http://www.byteclothing.com Edward

    Thank you so much for this series!!!! This has been so helpful in learning CodeIgniter!!!!

  • obaid

    you are using live server or local server for email to gmail??????????

  • obaid

    email is sent and no error occur but when i open my gmail account there was no email.
    But the message “your email is sent ,fool” was printed on browser
    please tell me the solution

    • Stole

      Hi, i have the same problem. Has anyone had similar? I get the success message but there is no email in my inbox?

  • pinar

    awesome tutorials! thanks for taking the time to make them :) keep them coming…

  • reza

    I love these tutorials. Thanks so much for teaching.

  • Nisho

    Thanks for sharing mate, these are just great tutorials!

  • http://none foo man

    This tutorial uses an older version of Code Igniter 1.7? So I made the adjustments for the CI_2.1 using the parent::__construct, but somehow I am still drawing a blank page from my URL http://localhost/shell/index.php/email/index. NO EMAIL WAS SENT FOOL….What should I do to get this to work? I can’t move onto the next tutorial and its frustrating :-/ Thanks in advance!

    ‘smtp’,
    ‘smtp_host’ => ‘ssl://smtp.googlemail.com’,
    ‘smtp_port’ => 465,
    ‘smtp_user’ => ‘user’,
    ‘smtp_pass’ => ‘pass’
    );

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

    $this->email->set_newline(“\r\n”);

    $this->email->from(‘rezapiri@gmail.com’, ‘Top Dog’);
    $this->email->to(‘rezapiri@gmail.com’);
    $this->email->subject(‘This is an email test’);
    $this->email->message(‘Its working’);

    if($this->email-send())
    {
    echo ‘Your email was sent fool.’;
    }

    else
    {
    show_error($this->email->print_debugger());
    }

    }

    }

  • http://none foo man

    the last post didn’t capture the controller etc…

    ‘smtp’,
    ‘smtp_host’ => ‘ssl://smtp.googlemail.com’,
    ‘smtp_port’ => 465,
    ‘smtp_user’ => ‘user’,
    ‘smtp_pass’ => ‘pass’
    );

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

    $this->email->set_newline(“\r\n”);

    $this->email->from(‘rezapiri@gmail.com’, ‘Top Dog’);
    $this->email->to(‘rezapiri@gmail.com’);
    $this->email->subject(‘This is an email test’);
    $this->email->message(‘Its working’);

    if($this->email-send())
    {
    echo ‘Your email was sent fool.’;
    }

    else
    {
    show_error($this->email->print_debugger());
    }

    }

    }

  • Jaiveek

    Ur videos r really very much helpful….thnks.. :)

  • alex

    Thanks for all you did. It’s very very good stuff. These videos can teach me a lot!!!

  • Muhammad Ashfaq

    I am seeing this error

    Parse error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION in C:\xampp\htdocs\ci\application\controllers\email.php on line 21

    Whlie my code is

    ‘smtp’ ,
    ‘smtp_host’ => ‘ssl://smtp.googlemail.com’ ,
    ‘smtp_port’ => ’465′ ,
    ‘smtp_user’ => ‘ashfaq202@gmail.com’ ,
    ‘smtp_pass’ => ‘*******’
    );
    }
    $this->load->library(‘email’, $config);
    $this->email->set_newline(‘\r\n’);

    $this->email->from(‘ashfaq202@gmail.com’, ‘Muhammad Ashfaq’);
    $this->email->to(‘ashfaq207@yahoo.com’);
    $this->email->subject(‘Testing my codeIgnitor Email’);
    $this->email->message(‘This is a perfect Software’);

    if($this->email->send())
    {
    echo ‘Email has been sent successfully’;
    }
    else
    {
    show_error($this->email->print_debugger());
    }
    }

  • http://lokconnect.com Rohit

    This took way too long. Windows Sucks!

    All the people who are facing openssl and socket errors inspite of opening ssl (uncommenting php_openssl.dll) in PHP.ini need to INSTALL openssl and Microsoft VC++ Redistibutable.

    Worked for me!

  • http://www.ideasmadevisual.com/ Thibault

    Most hosting providers this will work :

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

    $config['protocol'] = ‘sendmail’;
    $config['mailpath'] = ‘/usr/sbin/sendmail’;
    $config['charset'] = ‘iso-8859-1′;
    $config['wordwrap'] = TRUE;

    $this->email->initialize($config);

  • Pradeep

    Hi every one I am not able to send the mail I am getting a blank page, can anyone tell me if there are any major changes codeigniter latest version, that we need to apply in our code to make the code work.
    Thank you.

  • Codex

    Great series, thanks for producing this.

    One thing I noticed though is in the newer version of codeigniter, having this line produces an error when email.php is included in the config folder:

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

    It needs to be changed to just:

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

  • Farghana

    Just awesome tutorials!! I am learning Codeigniter thanks to you!

  • http://none mohammed

    Just awesome tutorials!! I am learning Codeigniter thanks to you!

    :D

  • http://rawdesigns.net/ Rob

    For whatever reason, I keep getting a 404 error. I’ve followed the video, and have updated my code to 2.0. Anyone help?

    My Code:

    ‘smtp’,
    ‘smtp_host’ => ‘ssl://smtp.googlemail.com’,
    ‘smtp_port’ => 465,
    ‘smtp_user’ => ‘######’,
    ‘smtp_pass’ => ‘######’
    );

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

    $this->email->from(‘robabby23@gmail.com’, ‘Rob Abby’);
    $this->email->to(‘robabby23@gmail.com’);
    $this->email->subject(‘This is an email’);
    $this->email->message(‘Its working!’);

    if ($this->email->send())
    {
    echo “Your email was sent, bitch!”;
    }

    else
    {
    show_error($this->email->print_debugger());
    }
    }

    }

    • http://rawdesigns.net Rob

      I realized that my 404 error had nothing to do with this Tut. I had followed the CodeIgniter Getting Started tut just before starting on these, and it had me declare a route that was overriding this controller.

      I commented out this line, and now I am getting the same SSL error as everyone else on windows, but at least its progress!

      Comment out this line if you have done the CI Docs Tut:

      $route['(:any)'] = ‘pages/view/$1′;

    • http://rawdesigns.net Rob

      Alright, I have updated my Code, my PHP.ini file, restarted Wamp, and now my page appears to just be stuck in a loading cylce…

  • http://vvdwivedi.com Vivek Dwivedi

    Hi,
    I am relatively new to CI, and mostly a windows user. Somehow this tutorial is not working for me. Its one error or the other and now its driving me crazy as to what wrong I am doing. I used the exact same code (with suggested modifications for new version) just to get errors like :

    “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?)”

    “fwrite() expects parameter 1 to be resource, boolean given”

    Generally I am not very good with debugging the codes, so if any additional data is required to solve these problems, please someone let me know. I am using xampp 1.7 on windows 7 64 bit, codeigniter 2.1

    Somebody please help me out.

  • http://www.dragoviandesign.be Peter Vermeulen

    When you move your email configuration to the separate email.php config file, you need to change your load function to

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

    instead of

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

    :) for the rest superb !

  • Chris

    I keep getting this error

    Message: file_exists() [function.file-exists]: open_basedir restriction in effect. File(/usr/local/apache/htdocs/newci/attachments/giants.jpg) is not within the allowed path(s): (/home/:/usr/lib/php:/tmp)

    Filename: libraries/Email.php

    Line Number: 1145

    so I got rid of

    $config['server_root'] = $_SERVER['DOCUMENT_ROOT'];

    From the config.php file and I changed the “email.php” file from

    $path = $this->config->item(‘server_root’);
    $file = $path . ‘/newci/attachments/giants.jpg’;

    $this->email->attach($file);

    and turned it into

    $file = ‘/newci/attachments/giants.jpg’;

    $this->email->attach($file);

    Now I don’t get any error’s , and my e-mail arrives, but I don’t get an attachment. Could anyone shed some light on this please?

  • Michel

    And even to date, this video is being enjoyed ! It’s all still working like a charm in version 2.1.0 (with some minor tweaks which people can find by googling the error)

    Tyvm !

  • Sanatan

    Awesome tutorial! Thanks a lot!!

  • Jmoola

    I’ve tried all above suggestions, but still get an error:

    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: 1553

    I’ve checked php.ini and all the settings seem to be good. Any suggestions? Thanks

  • Tom

    Thanks men!

  • juster

    I followed the tutorial. Emails can be send but I got a notice like this

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: config

    Filename: controllers/email.php

    Line Number: 13
    I am using codeigniter 2.1.0

    • Youssef

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

  • jester

    The codeigniter series is the best way to learn codeigniter

  • Andrew

    Hi, i need your help please, i have this error…

    Exit status code: 1
    Unable to open a socket to Sendmail. Please check settings.
    Unable to send email using PHP Sendmail. Your server might not be configured to send mail using this method.

  • Rahul Patil

    Hello,

    Thanks for valuable tutorials. These are the real Codeigniter tutorials IMHO..

    Anways, coming back to the point.

    As you said, we can autoload email config in /config/email.php.. I did exactly the same and tried to run the email function (localhost/project1/index.php/email). Though it sent email successfully, i got this error :

    A PHP Error was encountered

    Severity: Notice

    Message: Undefined variable: config

    Filename: controllers/email.php

    Line Number: 12

    • Rahul Patil

      Fixed it..

      Just remove $config from $this->load->library(‘email’,$config); as it is being auto loaded :)

      Regards.
      Rahul

  • http://tutjunction.com codeigniter

    nice tutorials

  • https://www.facebook.com/mdkovacevic Marko Kovacevic

    First of all I hope this will resolve all the problem with user using CI 2.0.x.

    Instead of creating arrays for cofig just pass data lik $config['port']=465, I will leave all of my code, don’t worry. Next as $config['mail_type'] put html, or u might get an error.

    $this->load->library(‘email’);// first we load library
    $this->email->set_newline(“\r\n”);//set the new line rule
    $config['charset'] = ‘utf-8′;
    $config['wordwrap'] = TRUE;
    $config['mailtype'] = ‘html’;
    $config['mailtype'] = ‘text’; // instead of html this is optional i just wanted to show other the default value in emal lib
    $config['protocol']=’smtp’;
    $config['smtp_port']=’465′;
    $config['smtp_host']=’ssl://smtp.googlemail.com’;
    $config['smtp_user']=#####@gmail.com’; // u put your mail here
    $config['smtp_pass']=’######’;// your pass

    $this->email->initialize($config);// crucial

    $this->email->from(‘#######@gmail.com ‘, ‘Marko Kovacevic’);
    $this->email->to(‘######@gmail.com’);

    $this->email->subject(‘Email Test’);
    $this->email->message(“The stuff works”);

    if($this->email->send())
    {
    echo “Mail sent “‘;
    }
    else{

    echo $this->email->print_debugger();

    And other part if you get error that you can’t send mai using PHP mail(), and your server in not configured you make changes in php.ini file(Win users might need to change LoadModule ssl, i think it is in httpd.conf file).

    [mail function]
    ; For Win32 only.
    ; http://php.net/smtp
    SMTP = ssl://googlemail.com
    ; http://php.net/smtp-port
    smtp_port = 465

    I hope i helped a litle ;)

    • skoolkaholic

      wow ! thanks ! :D

    • george

      thanks! now i can continue with the tutorial!

      • george

        replied to soon… not working for me :(

      • dfdf

        dfdf

      • http://www.facebook.com/shinde89 Rahul Shinde

        George can any way to attach file with CI ver. 2.1.3 Please revert

    • http://www.facebook.com/shinde89 Rahul Shinde

      Thanks after long time .. it succeed

  • Wangming

    help me alot

  • Ancol

    thank so much, this is great tutorial!

  • Pritam Roy

    this is awesome …I am only just learning php and I tried creating an email subscription list using raw php and almost bashed my head against the wall half way through….I think I am only just realizing just how awesome frameworks are :D

  • Stuart Blackett

    Nice tutorial. Very useful, even now!

    Just using the latest CI have spotted the $config is an undefined variable in the controller. Once you’ve shifted everything into the config/email.php file. So if anyones reading, any advisery to remove $config from the $this->load->library(‘email’);

    Also in the latest CI for a controller, you should try

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

  • Jan Paul

    I have this error, and enable ssl on my apache but now I get this error.

    Severity: Warning

    Message: fsockopen() [function.fsockopen]: unable to connect to ssl://smtp.googlemail.com:465 (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. )

    Filename: libraries/Email.php

  • http://www.computersneaker.com Mudasir Nazir

    Sorry in advance. But i was wondering for tutorials that are with code in text form, But i have got here a video tutorial. Can you please guide me from where i can get my CodeIgniter Tutorials But not in multimedia formats. Please

  • prem

    hey friend its working but the only problem i have that its not received by some of the active user and also and major problem is that how to prevent mail to go is spam box because mass mailing. and i tried to attach a file but its unable to find path…

    and we have a tamplate of our company and this just takes image path and how much time it opens it count as the mail received but that time it shows the error of mail header already sent can anyone help please.

  • Klaas

    Nice stuff, only the Gmail example does not work. I used the SMTP server of my own internet service provider and it works OK now.

    I created a email.php configuration file as described but noticed that the second parameter ($config) sould be removed from this call in the mail controller:
    $this->load->library(‘email’, $config);

    If not, the mail is still sent correctly but an error message is shown in the view:

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

    I did not see you remove the parameter but the error was not shown after your page reload…

  • http://www.valodustudija.lv Robert

    Could anyone approve, that this won’t work through Mac OS X 10.7.4, using MAMP (not PRO)?
    Or I just missed some kind of configuration steps?

    • Joshua Norvelle

      Most Apache stacks that you install locally aren’t able to send mail from your computer. They usually don’t come with the mail service because the ports they use are usually blocked by ISP, to stop spammers and what not.

  • http://www.thebuff.org Gaurav Komera

    perfecto :) thanks a lot…

  • Roberto

    Just finished this tutorial. Another great one.

    It’s Saturday and I have to do some chores, but once i’m done with the chores, I will go to the next one!

    Thank you!

    -Roberto

  • Marie

    Your tutorials are great! It’s a really great help. Thanks so much!