我在这里使用“Alin Purcaru”代码PHP mail() attachment problems 它适用于单个附件,但不适用于多个附件。 我最大的问题是随机输入文本输入之间的附件字段。
<input name="attach1" type="file" value=""/>
<input name="email" type="text" value=""/>
<input name="attach2" type="file" value=""/>
因此无法让所有事情都发挥作用。 我尝试了下面给出的同样问题的其他解决方案,但那些根本没有用。您能否告诉我如何更改此代码以用于多个附件?
答案 0 :(得分:1)
试试这个:
<input name="attach" type="file" value="" multiple/>
更新:
所以要完成我的回复,请按照以下步骤操作:
<强> mail.php 强>
定义一个帮助程序,以便从 apache 网站获取所有已知mimes类型的最新数组,我们稍后会在您的电子邮件附件中使用它们:
define('APACHE_MIME_TYPES_URL','http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types');
function generateUpToDateMimeArray($url){
$s=array();
foreach(@explode("\n",@file_get_contents($url))as $x)
if(isset($x[0])&&$x[0]!=='#'&&preg_match_all('#([^\s]+)#',$x,$out)&&
isset($out[1])&&($c=count($out[1]))>1)
for($i=1;$i<$c;$i++)
$s[]=' \''.$out[1][$i].'\' => \''.$out[1][0].'\'';
return @sort($s)?'$mime_types = array(<br />'.implode($s,',<br />').'<br />);':false;
}
定义一个帮助程序,避免显示所需的字符代替重音字符
function remove_accents($str, $charset='utf-8')
{
$str = htmlentities($str, ENT_NOQUOTES, $charset);
$str = preg_replace('#\&([A-za-z])(?:acute|cedil|circ|grave|ring|tilde|uml)\;#', '\1', $str);
$str = preg_replace('#\&([A-za-z]{2})(?:lig)\;#', '\1', $str);
$str = preg_replace('#\&[^;]+\;#', '', $str);
return $str;
}
处理数据并发送电子邮件:
function send_mail_with_attachments($sender, $name, $receiver, $subject, $message, $files = array()){
// Filtering some email servers that present bugs or different standards
if (!preg_match("#^[a-z0-9._-]+@(hotmail|live|msn|voila).[a-z]{2,4}$#", $receiver)){
$line_return = "\r\n";
}
// Other servers
else{
$line_return = "\n";
}
//===== Define text and html email format.
$message_txt = $message;
$message_html = "<html><head></head><body>".$message."</body></html>";
//==========
$i=0;
// Get mime types list
$mime_types= getLocalMimeTypes();
// Process attachments
foreach ($files as $filename) {
//=====Reading an attachment .
$file = fopen($filename, "r");
// Get its extension
$extension = strrchr($filename, '.');
$extension= str_replace('.', '', $extension);
// Store attachment content and some informations
$attachments[$i]['content'] = fread($file, filesize($filename));
$attachments[$i]['content'] = chunk_split(base64_encode($attachments[$i]['content']));
// File name
$attachments[$i]['filename'] = basename($filename);
// The file mime type
$attachments[$i]['type'] = $mime_types[$extension];
fclose($file);
$i++;
//==========
}
//=====Create the boundary.
$boundary = "-----=".md5(rand());
$boundary_alt = "-----=".md5(rand());
//==========
//=====Create the email header.
$header = "From: ".$name." <".$sender.">".$line_return;
$header.= "Reply-to: ".$name." <".$sender.">".$line_return;
$header.= "MIME-Version: 1.0".$line_return;
$header.= "Content-Type: multipart/mixed;".$line_return." boundary=\"$boundary\"".$line_return;
//==========
//=====Create the message.
$message = $line_return."--".$boundary.$line_return;
$message.= "Content-Type: multipart/alternative;".$line_return." boundary=\"$boundary_alt\"".$line_return;
$message.= $line_return."--".$boundary_alt.$line_return;
//=====Add text email
$message.= "Content-Type: text/plain; charset=\"ISO-8859-1\"".$line_return;
$message.= "Content-Transfer-Encoding: 8bit".$line_return;
$message.= $line_return.$message_txt.$line_return;
//==========
$message.= $line_return."--".$boundary_alt.$line_return;
//=====Add HTML email format.
$message.= "Content-Type: text/html; charset=\"ISO-8859-1\"".$line_return;
$message.= "Content-Transfer-Encoding: 8bit".$line_return;
$message.= $line_return.$message_html.$line_return;
//==========
//=====On ferme la boundary alternative.
$message.= $line_return."--".$boundary_alt."--".$line_return;
//==========
foreach ($attachments as $attachment) {
$message.= $line_return."--".$boundary.$line_return;
//=====Add attachment
$message.= "Content-Type: ".$attachment['type']."; name=\"".$attachment['filename']."\"".$line_return;
$message.= "Content-Transfer-Encoding: base64".$line_return;
$message.= "Content-Disposition: attachment; filename=\"".$attachment['filename']."\"".$line_return;
$message.= $line_return.$attachment['content'].$line_return.$line_return;
}
$message.= $line_return."--".$boundary."--".$line_return;
//==========
//=====Send it.
mail($receiver,$subjet,$message,$header);
//==========
}
<强> handlemail.php 强>
session_start();
require_once("mail.php");
// Get data
$sender = isset($_POST['mail_from'])? trim($_POST['mail_from']):'';
$name = isset($_POST['name'])? utf8_decode(utf8_encode(trim($_POST['name']))):'';
$receiver = isset($_POST['mail_to'])? trim($_POST['mail_to']):'';
// Do some character encoding for some servers
if (!preg_match("#^[a-z0-9._-]+@(yopmail|yahoo).[a-z]{2,4}$#", $receiver))
{
$subject = isset($_POST['objet'])? utf8_decode(utf8_encode(stripslashes(trim($_POST['objet'])))):'';
if (preg_match("#^[a-z0-9._-]+@(live|msn|outlook|hotmail).[a-z]{2,4}$#", $receiver)){
$msg = isset($_POST['msg'])? trim($_POST['msg']):'';
$msg =remove_accents($msg);
}
else
$msg = isset($_POST['msg'])? utf8_decode(utf8_encode(stripslashes(trim($_POST['msg'])))):'';
}
else{
if (!preg_match("#^[a-z0-9._-]+@(yahoo).[a-z]{2,4}$#", $receiver)){
$subject = isset($_POST['objet'])? trim($_POST['objet']):'';
$subject = remove_accents($subject);
}
else
$subject = isset($_POST['objet'])? utf8_decode(utf8_encode(stripslashes(trim($_POST['objet'])))):'';
$msg = isset($_POST['msg'])? trim($_POST['msg']):'';
$msg = remove_accents($msg);
}
if($sender =='' || $name =='' || $receiver == '' || $subject == '' || $msg == ''){
$error= true;
}
if(!$error){
// We prepare our attachments new path on server
$attachments = array();
// We make an array of allowed extension, feel free to add new extensions or remove from the list
$extensions = array('.png', '.gif', '.jpg', '.jpeg', '.pdf', '.doc', '.docx', '.mp3', '.mp4', '.aac', '.xls', '.txt', '.zip', '.rar', '.tar.gz', '.7z');
// maximum attachment size (Bytes)
$max_size = 3000000;
for($i=0; $i<count($_FILES['upload']['name']); $i++) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
$filename = basename($_FILES['upload']['name'][$i]);
//Make sure we have a filepath
if ($tmpFilePath != ""){
// get the file extension
$extension = strrchr($_FILES['upload']['name'][$i], '.');
//Ensuite on teste
if(!in_array($extension, $extensions))
{
$erreur = 'The extension '.$extension.' is not allowed...';
$error = true;
continue;
}
//File size
$size = filesize($_FILES['upload']['tmp_name'][$i]);
if($size>$max_size)
{
$erreur = 'This file is too big...';
$error = true;
continue;
}
//Encode the filename...
$filename = strtr($filename,
'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðòóôõöùúûüýÿ',
'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
$filename = preg_replace('/([^.a-z0-9]+)/i', '-', $filename);
//Setup our new file path
$newFilePath = dirname(__FILE__)."/uploadFiles/".$filename;
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$attachments[]= $newFilePath;
}
}
}
if(!$error) send_mail_with_attachments($sender, $name, $receiver, $subject, $msg, $attachments);
}
session_unset();
session_destroy();
if(!$error)
header("location:./form.php?sended=1");
else
header("location:./form.php?error=1");
<强> HTML 强>
使用以下内容为每个附件定义文件输入:
<input name="upload[]" type="file"/>