這是我做了什麼發送郵件附加換貨。有些代碼是我的,其中一些代碼來自http://php.net/manual/en/function.mail.php。此代碼已經過嘗試和測試,因此它應該可以工作。還看看是否安裝了sendmail。如果在linux的ubuntu系統上試試sudo apt-get install sendmail來安裝它。 有關此代碼的最佳部分是它適用於多個文件上載。
文件名:index.php文件
<?php
if($_POST || $_FILES)
{
// email fields: to, from, subject, and so on
// Here
$from = "[email protected]";
$to = "[email protected]_else.com";
$subject = "Mail with Attachment";
$message = "This is the message body and to it I will append the attachments.";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n"."Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
fixFilesArray($_FILES['attachment']);
foreach ($_FILES['attachment'] as $position => $file)
{
// should output array with indices name, type, tmp_name, error, size
$message .= "--{$mime_boundary}\n";
$fp = @fopen($file['tmp_name'],"rb");
$data = @fread($fp,filesize($file['tmp_name']));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".$file['name']."\"\n"."Content-Description: ".$file['name']."\n" ."Content-Disposition: attachment;\n" . " filename=\"".$file['name']."\";size=".$file['size'].";\n"."Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $from;
$ok = @mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return 1; } else { return 0; }
}
//This function will correct file array from $_FILES[[file][position]] to $_FILES[[position][file]] .. Very important
function fixFilesArray(&$files)
{
$names = array('name' => 1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
foreach ($files as $key => $part) {
// only deal with valid keys and multiple files
$key = (string) $key;
if (isset($names[$key]) && is_array($part)) {
foreach ($part as $position => $value) {
$files[$position][$key] = $value;
}
// remove old key reference
unset($files[$key]);
}
}
}
?>
<html>
<body>
<form method="POST" action="index.php" enctype="multipart/form-data">
<input type="file" name="attachment[]"><br/>
<input type="submit">
</form>
</body>
</html>
通過我願意爲使用sendmail,因爲它是慢了一點道歉的方式。我會嘗試發佈更好的解決方案。