将上传的文件作为电子邮件附件

时间:2016-12-17 08:40:51

标签: php email-attachments

我有一个带文件上传的表单。表单提交后,应该通过电子邮件发送文件。我使用的是一个简单的PHP脚本,但它不起作用。

如何通过电子邮件发送上传的文件?

//Send Mail
        $file_tmp_name = $_FILES['file']['tmp_name'];
    $file_name = $_FILES['file']['name'];
    $file_size = $_FILES['file']['size'];
    $file_type = $_FILES['file']['type'];

//read from the uploaded file & base64_encode content for the mail
        $handle = fopen($file_tmp_name, "r");
        $content = fread($handle, $file_size);
        fclose($handle);
        $encoded_content = chunk_split(base64_encode($content));


        $boundary = md5("sanwebe");
        //header
        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "From:".$mail."\r\n";
        $headers .= "Reply-To: ".$mail."" . "\r\n";
        $headers .= "Content-Type: multipart/mixed; boundary = ".$boundary."\r\n\r\n";

        //plain text
        $body = "--".$boundary."\r\n";
        $body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
        $body .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $body .= chunk_split(base64_encode($message));

        //attachment
        $body .= "--".$boundary."\r\n";
        $body .="Content-Type: ".$file_type."; name=".$file_name."\r\n";
        $body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
        $body .="Content-Transfer-Encoding: base64\r\n";
        $body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
        $body .= $encoded_content;


        send_mail($to,$subject,$body,$headers);

1 个答案:

答案 0 :(得分:0)

您的表单中是否有enctype='multipart/form-data'参数? 例如:<form name="form_name" action="send.php" method="post" enctype='multipart/form-data'>