CodeIgniter重命名电子邮件附件文件

时间:2013-08-08 14:09:59

标签: php codeigniter email codeigniter-2

我有CodeIgniter脚本,用于发送带附件的电子邮件。

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

它的效果很好,但我不知道如何将附加文件重命名为更友好的用户字符串?

2 个答案:

答案 0 :(得分:11)

CodeIgniter v3.x

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

根据user guide

  

如果您想使用自定义文件名,可以使用第三个   参数:

     

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


CodeIgniter v2.x

但是对于CodeIgniter v2.x,您可以扩展Email库来实现:

  1. 创建system/libraries/Email.php的副本并将其放在application/libraries/
  2. 重命名该文件并添加MY_前缀(或您在config.php中设置的任何内容)application/libraries/MY_Email.php
  3. 打开文件并更改以下内容:
  4. 首先: #72 行插入此内容:

    var $_attach_new_name = array();
    

    第二次:将 #161-166 行的代码更改为:

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

    第三: #409 行找到attach()功能并将其更改为:

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

    第四:最后在 #1143 行将代码更改为:

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

    用法

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

答案 1 :(得分:1)

此方法也适用于 CodeIgniter v1.7x

但你一定不要忘记修改下面的这个函数来添加$this->_attach_new_name也被清理:

public function clear($clear_attachments = FALSE){
    $this->_subject     = "";
    $this->_body        = "";
    $this->_finalbody   = "";
    $this->_header_str  = "";
    $this->_replyto_flag = FALSE;
    $this->_recipients  = array();
    $this->_cc_array    = array();
    $this->_bcc_array   = array();
    $this->_headers     = array();
    $this->_debug_msg   = array();
    $this->_set_header('User-Agent', $this->useragent);
    $this->_set_header('Date', $this->_set_date());
    if ($clear_attachments !== FALSE){
        $this->_attach_new_name = array();
        $this->_attach_name     = array();
        $this->_attach_type     = array();
        $this->_attach_disp     = array();
    }
    return $this;
}  
相关问题