发送
我正在尝试上传一个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@example.comrnReply-To: webmaster@example.com";
$headers .= "rnMIME-Version: 1.0rnContent-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");
我收到了电子邮件,但有一堆垃圾短信,看起来$边界会产生大量垃圾短信。或者我做错了,首先我必须将文件上传到服务器中的某个位置,然后通过电子邮件
我一直喜欢手动滚动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.0n" . "Content-Type: multipart/mixed;n" . " boundary="{$mime_boundary}"";
// multipart boundary
$message = "This is a multi-part message in MIME format.nn" . "--{$mime_boundary}n" . "Content-Type: text/plain; charset="iso-8859-1"n" . "Content-Transfer-Encoding: 7bitnn" . $message . "nn";
$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: base64nn" . $data . "nn";
$message .= "--{$mime_boundary}n";
$ok = @mail($to, $subject, $message, $headers, "-f " . $from);