Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用php发送附件_Php_Email - Fatal编程技术网

用php发送附件

用php发送附件,php,email,Php,Email,我正在尝试创建一个电子邮件表单,允许您发送附件。我从我的PHP书和几个网站上拼凑了代码 当我使用此表单发送电子邮件时,附件最终损坏,“$comments”似乎无法通过 以下是我正在使用的代码: <?php $to = $_POST['to']; $from = $_POST['from']; $re = $_POST['re']; $comments= $_POST['comments']; $att = $_FILES['att']; $att_path= $_FILES['att']

我正在尝试创建一个电子邮件表单,允许您发送附件。我从我的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";

?>

那么,我做错了什么


谢谢

你最好使用或

我想你会发现使用类似PHPMailer的东西更容易

试试这个来编码你的文件以便传输

更换线路:

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

希望您已经尝试过(注意边界的拼写):


斯威夫特·梅勒看起来不错,但是,这个建议是为了提高我的PHP技能,所以我想知道我做错了什么,这样我可以改进它。你可以查看他们的来源,他们有方便的方法来添加各种附件。这些代码似乎只是将附件放在消息文本中。请参阅PEAR项目中的Mail_Mime类,谢谢,我已经解决了这个问题,但我仍然有相同的问题。
  //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)); 
$str = "==Multipart_Boumdary_x{$num}x";
$str = "==Multipart_Boundary_x{$num}x";