在电子邮件中附加base64_encoded字符串 - Codeigniter

时间:2012-05-09 09:44:26

标签: php codeigniter

我花了最后一天创建了一个脚本,当客户从我们的网站购买东西时,该脚本将创建一个PDF收据。创建PDF后,我使用ob_get_clean()

将输出保存到变量中

然后我将此变量变为base64_encoded字符串。当我这样做时,我将字符串保存到数据库。现在,我想要做的就是获取字符串并以某种方式将其保存为电子邮件的附件,以便用户可以将其作为文件下载。我试过Google,但我找不到任何有用的东西。

我找到了这个帖子,但据我在Codeigniter电子邮件库中看到的(我可能已经错过了它),请求的功能没有实现。这是请求Email class: add attachment from string

2 个答案:

答案 0 :(得分:2)

您可以使用php mail函数和相应的标题创建自己的库并发送电子邮件。

function send_email($to, $from, $subject, $body, $attachment_string)
{

$filename = "receipt.pdf";
$uid = md5(uniqid(time())); 
$attachment=chunk_split($attachment_string);

$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$headers .= "From: <".$from.">\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-type:text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $body."\r\n\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-Type: application/pdf; name=\"".basename($filename)."\"\r\n"; // use different content types here
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".basename($filename)."\"\r\n\r\n";
$headers .= $attachment."\r\n\r\n";
$headers .= "--".$uid."--";

if(mail($to, $subject, $body, $headers))
{
    echo "success";
}

}

答案 1 :(得分:0)

在codeigniter Email类中,当我们将mime类型作为参数传递时,执行以下代码。

$file_content =& $file; // buffered file

$this->_attachments[] = array(
        'name'      => array($file, $newname),
        'disposition'   => empty($disposition) ? 'attachment' :    $disposition,  // Can also be 'inline'  Not sure if it matters
        'type'      => $mime,
        'content'   => chunk_split(base64_encode($file_content)),
        'multipart' => 'mixed'
    );

chunk_split(base64_encode($file_content))会破坏我们传递给$this->email->attach()函数的base64文件。

因此我将代码更改为

    $file_content =& $file; // buffered file
    $file_content = ($this->_encoding == 'base64') ? $file_content   :  chunk_split(base64_encode($file_content));

现在附件数组为:

 $this->_attachments[] = array(
        'name'      => array($file, $newname),
        'disposition'   => empty($disposition) ? 'attachment' :  $disposition,  // Can also be 'inline'  Not sure if it matters
        'type'      => $mime,
        'content'   => $file_content,
        'multipart' => 'mixed'
    );

现在,当我通过电子邮件发送电子邮件时:

   $config['_bit_depths'] = array('7bit', '8bit','base64');
   $config['_encoding'] = 'base64'
   $this->load->library('email',$config);

可能是我做错了,但它确实有效。

   $this->email->attach($base64,'attachment','report.pdf','application/pdf');     

下载修改后的电子邮件类:

https://github.com/aqueeel/CI-Base64EmailAttach