使用CodeIgniter从URL发送PDF邮件附件时文件损坏问题
解决CodeIgniter邮件URL附件损坏问题
直接使用URL作为附件时,CodeIgniter的Email库可能因未正确处理远程文件的二进制流,导致附件内容被篡改,最终无法正常打开。以下是两种可靠的解决方案:
方案一:先下载远程PDF到本地临时文件再附加
通过将远程文件下载到服务器临时目录,再附加本地文件的方式,避免直接处理URL时的编码或流读取问题:
$this->load->library('email'); // 下载远程PDF到临时文件 $remote_pdf_url = 'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'; $temp_file = tempnam(sys_get_temp_dir(), 'pdf_'); file_put_contents($temp_file, file_get_contents($remote_pdf_url)); // 配置邮件参数 $this->email->from(EMAIL_ADDRESS, EMAIL_NAME); $this->email->to('test@example.com'); $this->email->subject("Email Subject"); $this->email->message("Please find attached file"); // 附加本地文件,明确指定MIME类型 $this->email->attach($temp_file, 'attachment', 'dummy.pdf', 'application/pdf'); // 发送邮件 $this->email->send(); // 清理临时文件(可选) unlink($temp_file);
方案二:直接以字符串形式附加文件内容
利用CodeIgniter Email库的字符串附加功能,直接传入远程文件的二进制内容,同时指定文件名和MIME类型:
$this->load->library('email'); // 获取远程PDF的二进制内容 $pdf_content = file_get_contents('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf'); // 配置邮件参数 $this->email->from(EMAIL_ADDRESS, EMAIL_NAME); $this->email->to('test@example.com'); $this->email->subject("Email Subject"); $this->email->message("Please find attached file"); // 以字符串形式附加PDF $this->email->attach($pdf_content, 'string', 'dummy.pdf', 'application/pdf'); $this->email->send();
补充说明
- 若服务器禁用了
allow_url_fopen,可改用cURL获取远程文件:
function get_remote_file($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); $data = curl_exec($ch); curl_close($ch); return $data; } // 使用示例 $pdf_content = get_remote_file('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');
- 确保Email库的
protocol配置正确(如SMTP),避免因邮件传输编码问题导致附件损坏。
内容的提问来源于stack exchange,提问作者Irfan Ullah
相关产品推荐
相关产品推荐

