Search code examples
phpcodeigniteremailcodeigniter-2

CodeIgniter rename email attachment file


I have CodeIgniter script for sending email with attachments.

$this->ci->email->attach("/path/to/file/myjhxvbXhjdSycv1y.pdf");

It works great, but I have no idea, how rename attached file to some more user-friendly string?


Solution

  • CodeIgniter v3.x

    This feature has been added since CI v3:

    /**
     * Assign file attachments
     *
     * @param   string  $file   Can be local path, URL or buffered content
     * @param   string  $disposition = 'attachment'
     * @param   string  $newname = NULL
     * @param   string  $mime = ''
     * @return  CI_Email
     */
    public function attach($file, $disposition = '', $newname = NULL, $mime = '')
    

    According to the user guide:

    If you’d like to use a custom file name, you can use the third parameter:

    $this->email->attach('filename.pdf', 'attachment', 'report.pdf');


    CodeIgniter v2.x

    However for CodeIgniter v2.x, you can extend the Email library to implement that:

    1. Create a copy of system/libraries/Email.php and put it inside application/libraries/
    2. Rename the file and add MY_ prefix (or whatever you have set in config.php) application/libraries/MY_Email.php
    3. Open the file and change the following:

    First: Insert this at line #72:

    var $_attach_new_name = array();
    

    Second: Change the code at line #161-166 to:

    if ($clear_attachments !== FALSE)
    {
        $this->_attach_new_name = array();
        $this->_attach_name     = array();
        $this->_attach_type     = array();
        $this->_attach_disp     = array();
    }
    

    Third: Find the attach() function at line #409 and change it to:

    public function attach($filename, $disposition = 'attachment', $new_name = NULL)
    {
        $this->_attach_new_name[] = $new_name;
        $this->_attach_name[]     = $filename;
        $this->_attach_type[]     = $this->_mime_types(pathinfo($filename, PATHINFO_EXTENSION));
        $this->_attach_disp[]     = $disposition; // Can also be 'inline'  Not sure if it matters
        return $this;
    }
    

    Fourth: Finally at line #1143 change the code to:

    $basename = ($this->_attach_new_name[$i] === NULL)
        ? basename($filename) : $this->_attach_new_name[$i];
    

    Usage

    $this->email->attach('/path/to/fileName.ext', 'attachment', 'newFileName.ext');