开发者

Attach file to mail using php

I've created a form which contains an upload field file and some other text fields. I'm using php to send the form's data via email and attach the file.

This is the code I'm using but it's not working properly. The file is normally attached to the message but the rest of the data is not sent.

$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/octe开发者_运维知识库t-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="test@test.com";
mail($to,$subject,$message,$headers);

Why isn't the $body data not sent? Can you help me fix it?


Well, I'd suggest using the PEAR Mail_Mime package... It abstracts all that away...

As for your exact issue, I'd guess it's because you have two different boundaries and two Content-Type headers in the header section. Try generating something like this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜