2010-06-07 84 views
0

我創建了一個包含上傳字段文件和其他一些文本字段的表單。我使用PHP通過電子郵件發送表單的數據並附加文件。使用php附加文件到郵件

這是我正在使用的代碼,但它不能正常工作。該文件通常附加到消息,但其餘數據不會發送。

$body="bla bla bla"; 

$attachment = $_FILES['cv']['tmp_name']; 
$attachment_name = $_FILES['cv']['name']; 
if (is_uploaded_file($attachment)) { 
    $fp = fopen($attachment, "rb"); 
    $data = fread($fp, filesize($attachment)); 
    $data = chunk_split(base64_encode($data)); 
    fclose($fp); 
} 

$headers = "From: $email<$email>\n"; 
$headers .= "Reply-To: <$email>\n"; 
$headers .= "MIME-Version: 1.0\n"; 
$headers .= "Content-Type: multipart/related; type=\"multipart/alternative\"; boundary=\"----=MIME_BOUNDRY_main_message\"\n"; 
$headers .= "X-Sender: $first_name $family_name<$email>\n"; 
$headers .= "X-Mailer: PHP4\n"; 
$headers .= "X-Priority: 3\n"; 
$headers .= "Return-Path: <$email>\n"; 
$headers .= "This is a multi-part message in MIME format.\n"; 
$headers .= "------=MIME_BOUNDRY_main_message \n"; 
$headers .= "Content-Type: multipart/alternative; boundary=\"----=MIME_BOUNDRY_message_parts\"\n"; 

$message = "------=MIME_BOUNDRY_message_parts\n"; 
$message .= "Content-Type: text/html; charset=\"utf-8\"\n"; 
$message .= "Content-Transfer-Encoding: quoted-printable\n"; 
$message .= "\n"; 
$message .= "$body\n"; 
$message .= "\n"; 
$message .= "------=MIME_BOUNDRY_message_parts--\n"; 
$message .= "\n"; 
$message .= "------=MIME_BOUNDRY_main_message\n"; 
$message .= "Content-Type: application/octet-stream;\n\tname=\"" . $attachment_name . "\"\n"; 
$message .= "Content-Transfer-Encoding: base64\n"; 
$message .= "Content-Disposition: attachment;\n\tfilename=\"" . $attachment_name . "\"\n\n"; 
$message .= $data; //The base64 encoded message 
$message .= "\n"; 
$message .= "------=MIME_BOUNDRY_main_message--\n"; 

$subject = 'bla bla bla'; 
$to="[email protected]"; 
mail($to,$subject,$message,$headers); 

爲什麼沒有發送$ body數據?你能幫我解決嗎?

回答

1

嗯,我會建議使用PEAR Mail_Mime包......它抽象一切了......

至於你確切的問題,我猜那是因爲你有兩個不同的邊界和兩個內容 - 在標題部分中輸入標題。嘗試生成這樣的事情:

MIME-Version: 1.0 
Content-Type: multipart/mixed; boundary="------=MIME_BOUNDARY_MESSAGE_PARTS" 

------=MIME_BOUNDARY_MESSAGE_PARTS 
Content-Type: text/html charset="utf-8" 

$body 

------=MIME_BOUNDARY_MESSAGE_PARTS 
Content-Type: application/octet-stream;name="filename" 
Content-Transfer-Encoding: base64 
... 
$data 

------=MIME_BOUNDARY_MESSAGE_PARTS 
+0

是的郵件庫真的有幫助。我使用迅捷郵件。 – gunnx 2012-05-10 15:18:06