Php 通过html表单发送文件附件会向电子邮件正文发送大量垃圾文本
我试图使一个html文件上传发送通过电子邮件与php。以下是代码片段:Php 通过html表单发送文件附件会向电子邮件正文发送大量垃圾文本,php,email,attachment,Php,Email,Attachment,我试图使一个html文件上传发送通过电子邮件与php。以下是代码片段: $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name']))); $filename = $_FILES['file']['name']; $boundary =md5(date('r', time())); $headers = "From: webmaster
$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生成了一堆垃圾文本。或者我做错了,首先我必须将文件上传到服务器的某个地方,然后通过电子邮件发送。我也一直喜欢像你这样手动滚动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);