将base64字符串转换成邮件附件pdf

时间:2016-10-11 13:18:19

标签: php email pdf base64 attachment

我有这个代码,它将PDF编码文件作为从另一个窗口生成的Base64 URI字符串,并被声明为php会话变量,最后这是我编码的函数,它发送电子邮件但是Base64解码为大量的字符,而不是正确完成的附件。

function MailWithAttachment($to, $subject, $message, $senderMail, $senderName, $files){

$from = $senderName." <".$senderMail.">"; 
$headers = "From: $from";$headers = "MIME-Version: 1.0$newline".
       "Content-Type: application/pdf;".
       "boundary = \"$boundary\"$newline$newline".
       "--$boundary$newline".
       "Content-Type: application/pdf; charset=ISO-8859-1$newline; Content-Disposition: attachment;".
       "Content-Transfer-Encoding: base64$newline$newline"; 
echo "<script>alert('$files')</script>";
$headers .= rtrim(chunk_split($files));
$returnpath = "-f" . $senderMail;
//send email
$mail = @mail($to, $subject, $message, $headers, $returnpath); 
if($mail){ return TRUE; } else { return FALSE; }
}

1 个答案:

答案 0 :(得分:2)

最后,我之前解码了我的base64 pdf文件并将解码后的字符串保存到变量中,并在附件属性中设置了该变量。

BTW,我使用过PHP Mailer

<?php
$_SESSION["sesDataPDF"] = $_POST["hdn_UriPdf"];
$b64file = $_SESSION["sesDataPDF"];
$decodPdf;
if ($b64file){
    $nomPdf = ;
    $nomPdf .= ".pdf";
    $nomPdf = (string)$nomPdf;
    $b64file= trim(str_replace('data:application/pdf;base64,', "", $b64file) );
    $b64file= str_replace( ' ', '+', $b64file);
    $decodPdf= base64_decode($b64file);
    file_put_contents($nomPdf, $decodPdf);
    $mail = new PHPMailer;
    $mail->isSendmail();
    $mail->setFrom('', '');
    $mail->addAddress($mail, $name);
    //Set the subject line
    $mail->Subject = '';
    $mail->Body = '';
    $mail->AltBody = '';
    $mail->addAttachment($nomPdf);
    $mail->Timeout=60;
}
?>