0

我正在尝试使用 php 上传 html 文件以通过电子邮件发送。这是代码片段:

$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
        $filename = $_FILES['file']['name'];
        $boundary =md5(date('r', time())); 
        $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
        $headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";

        $body="This is a multi-part message in MIME format.

        --_1_$boundary
        Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

        --_2_$boundary
        Content-Type: text/plain; charset=\"iso-8859-1\"
        Content-Transfer-Encoding: 7bit

        test

        --_2_$boundary--
        --_1_$boundary
        Content-Type: application/octet-stream; name=\"$filename\" 
        Content-Transfer-Encoding: base64 
        Content-Disposition: attachment 

        $attachment
        --_1_$boundary--";

        mail('email@example.com', 'Leidige stillinger', $body, $headers) or die("NO");

我收到了电子邮件,但带有垃圾文本,看起来 $boundary 生成了一大堆文本。或者我做错了,首先我必须将文件上传到服务器的某个地方,然后通过电子邮件发送

4

1 回答 1

0

我也一直喜欢手动滚动 MIME 编码,就像你正在做的那样,而不是使用库。你很近。尝试这个:

    // to, from, subject, message body, attachment filename, etc.
    $to = "to@to.com";
    $from = "from@from.com";
    $subject = "subject";
    $message = "this is the message body";
    $filename="/home/user/file.pdf";  //location of file - path and filename
    $fname="file.jpeg";               //name of file for display purposes 

    $headers = "From: $from"; 
    // boundary 
    $semi_rand = md5(time()); 
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 

    // headers for attachment 
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\""; 

    // multipart boundary 
    $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
    $message .= "--{$mime_boundary}\n";

    // preparing attachments            
        $file = fopen($filename,"rb");
        $data = fread($file,filesize($fname));
        fclose($file);
        $data = chunk_split(base64_encode($data));
        $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$fname\"\n" . 
        "Content-Disposition: attachment;\n" . " filename=\"$fname\"\n" . 
        "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
        $message .= "--{$mime_boundary}\n";


    $ok = @mail($to, $subject, $message, $headers, "-f " . $from);          
于 2013-07-12T15:01:19.510 回答