使用php将文件附加到邮件

时间:2010-06-07 12:03:40

标签: php file forms email

我创建了一个包含上传字段文件和其他一些文本字段的表单。我正在使用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="test@test.com";
mail($to,$subject,$message,$headers);

为什么不发送$ body数据?你能帮我解决一下吗?

1 个答案:

答案 0 :(得分:1)

好吧,我建议使用PEAR Mail_Mime软件包......它将所有内容抽象出来......

至于你的确切问题,我猜是因为你在标题部分有两个不同的边界和两个Content-Type标题。尝试生成这样的东西:

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