Pass File via mail() PHP

百般思念 提交于 2019-12-24 20:37:57

问题


I have a Problem, I would like to send a File (Photoshop, .gif etc.) File via Email with PHP. I POST the Data from the HTML Document to the following PHP File. The Problem: I receive the Email but the File is corrupt. Any Idea why this doesn´t work??

    $to = 'admin@example.com'; 
    $subject = 'Order';

    $name = strip_tags($_POST['name']);
    $email = strip_tags($_POST['email']);
    $plz = strip_tags($_POST['plz']);
    $city = strip_tags($_POST['city']);
    $street = strip_tags($_POST['street']);
    $nr = strip_tags($_POST['nr']);

    $plzdelivery = strip_tags($_POST['plz-delivery']);
    $citydelivery = strip_tags($_POST['city-delivery']);
    $streetdelivery = strip_tags($_POST['street-delivery']);
    $nrdelivery = strip_tags($_POST['nr-delivery']);

    $buttonsize = strip_tags($_POST['button-size']);
    $count = strip_tags($_POST['count']);

    $message = "Name: ".$name." Email: ".$email." Plz: ".$plz." Stadt: ".$city." Strasse: ".$street." Hnr: ".$nr." Button: ".$buttonsize." Anzahl: ".$count;

    $type = $_FILES['file']['type'];
    $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\"";

    $message="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

$message

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

$attachment
--_1_$boundary--";

    mail($to, $subject, $message, $headers);

回答1:


Short answer: Don't even try.

PHP's mail() function is very very short on features. If you're even considering trying to send attachments using it, you are in for a lot of frustration and wasted time.

The best answer I can give you is to use a third party library. There are several good ones available. Why waste weeks of your time writing something that isn't going to be good enough when others have already spent years doing it for you and getting it right.

My suggestion would be phpMailer, but several others exist as well.




回答2:


You should install the pear Mail_Mime package, it will allow you to easily attach a file.

http://pear.php.net/manual/en/package.mail.mail-mime.addattachment.php



来源:https://stackoverflow.com/questions/15056190/pass-file-via-mail-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!