Clearing Attachments Using CodeIgniter’s Email Class

November 4th, 2010 - Posted by Steve Marks to PHP, Web Development.

The CodeIgniter Email Class makes it very simple to send emails by handling the creation of mail headers and more on your behalf. My favourite benefit of the class however is it’s attachment handling. Whereas using standalone PHP it would take multiple lines of complex code to attach a single file, CodeIgniter allows us to do the same thing by calling just one function like so:


I had a problem recently however where I had attached a file using the above code, sent the email and needed to send another email straight after in the same script. As outlined in the CodeIgniter documentation I used the following code to clear all the variables and begin a fresh email:


This seemed to work to a degree. The attachment however was still coming through on the second email, even after calling the clear() function.

So how do I clear the attachments as well?

After reading further into the documentation I found that there is an optional boolean parameter that can be passed to the email classes clear() function that, if set to TRUE, will clear attachments also. It turns out that by default attachments are not removed. Our code should now look as follows:


Voila! No more attachments on the following emails sent out.

This entry was posted on Thursday, November 4th, 2010 at 10:01 pm by +Steve Marks and is filed under PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (8)
  1. Sarah says:


  2. shivraj chari says:

    Hi,thanks a lot. :)

  3. @Davi – If you want to attach photos that are uploaded you will need to save them to the local filesystem somewhere first, perhaps in a temporary directory, then attach them.

    See here for how to store the the file somewhere:

    Then you can attach it using:


    Hope that helps :)

  4. Davi Menezes says:

    Hello friend, as it does to send attachment sent form?
    Ex: $ file = $ this-> input-> post (‘field name file’);
    when entering the command $ this-> email-> attach ($ file), it sends only the name of the File, the attachment is not sent.
    I’ve tried to include this within the function: … attach ($ _FILE [‘field name’] [‘tmp_name’]); And so it sends the attachment ok, but with the extension. “tmp”.
    What is the correct way to send a file attachment via email?

  5. ahmd says:

    thanx allllllllllllllllllllllllllllllot

  6. rj says:

    Thanks!!! Had same problem.

  7. Simon says:

    Bravo! I was wondering why the ‘clear’ function wasn’t working. Thanks

  8. Rob says:

    Thank you for this!