用php发送附件

时间:2009-09-29 03:06:52

标签: php email

我正在尝试创建一个允许您发送附件的电子邮件表单。我已经从我的PHP书和几个网站拼凑了代码。

当我使用此表单发送电子邮件时,附件最终损坏,“$ comments”似乎没有通过。

以下是我正在使用的代码:

<?php
$to = $_POST['to'];
$from = $_POST['from'];
$re = $_POST['re'];
$comments= $_POST['comments'];

$att = $_FILES['att'];
$att_path= $_FILES['att']['tmp_name'];
$att_name = $_FILES['att']['name'];
$att_size = $_FILES['att']['size'];
$att_type = $_FILES['att']['type'];

//open, read, then close the file
$fp = fopen( $att_path, "rb" );
$file = fread( $fp, $att_size );
fclose($fp);

#create a boundary string
$num = md5(time());
$str = "==Multipart_Boumdary_x{$num}x";

//encode the data for transit
$file = chunk_split(base64_encode($file));

//define header
$hdr = "MIME-Versio: 1.0\r\n";
$hdr .= "Content-Type: multipart/mixed; ";
$hdr .= "boundary=\"{$str}\"\r\n";
$hdr .= "From: $from \r\n";

#define message
$msg = "This is a multi-part message in MIME format\r\n\n";
$msg .= "--{$str}\r\n";
$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n";
$msg .= "$comments\r\n\n";
$msg .= "--{$str}\r\n";

#define the non-text attatchment
$msg .= "Content-Type: {$att_type}; ";
$msg .= "name=\"{$att_name}\"\r\n";
$msg .= "Content-Disposition: attachment; ";
$msh .= "filename=\"{$att_name}\"\r\n";
$msg .= "Content-Transfer-Encoding: base64\r\n";
$msg .= "$file\r\n\n";
$msg .= "--{$str}";

#sendmail
$ok = mail( $to, $re, $msg, $hdr );
if( $ok ) echo "OK";

?>

那么,我做错了什么?

谢谢!

4 个答案:

答案 0 :(得分:2)

答案 1 :(得分:0)

我认为你会发现使用像PHPMailer http://phpmailer.worxware.com/index.php?pg=phpmailer

这样的东西更容易

答案 2 :(得分:0)

请尝试将此文件编码为传输。

替换行:

  $file = chunk_split(base64_encode($file));

使用:

  //Encode the file for transit
  $content = '';
  $fp = fopen($att_path, 'r'); 
  do { 
    $data = fread($fp, 8192); 
    if (strlen($data) == 0) break; 
    $content .= $data; 
  } while (true); 
  $file = chunk_split(base64_encode($content)); 

答案 3 :(得分:0)

$str = "==Multipart_Boumdary_x{$num}x";

希望你已经尝试过(注意bouNdary的拼写):

$str = "==Multipart_Boundary_x{$num}x";