0

i am using "Alin Purcaru" code from here PHP mail() attachment problems It's working great with single attachment but not for multiple attachments. My big problem is am having attachment fields between text inputs randomly.

<input name="attach1" type="file" value=""/>
<input name="email" type="text" value=""/>
<input name="attach2" type="file" value=""/>

So can't get it work all things. I tried other solutions given below for the same question but those aren't working at all. Can you some one show me how to change this code to work for multiple attachments?

Community
  • 1
  • 1
devdarsh
  • 95
  • 2
  • 10

1 Answers1

1

Try this:

<input name="attach" type="file" value="" multiple/>

UPDATE:

So to complete my response, follow those steps:

mail.php

  1. Define a helper to get an up to date array of all known mimes types from apache website, we need them in your email attachments later:

    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[]='&nbsp;&nbsp;&nbsp;\''.$out[1][$i].'\' => \''.$out[1][0].'\'';
        return @sort($s)?'$mime_types = array(<br />'.implode($s,',<br />').'<br />);':false;
    }
    
  2. Define a helper that avoids displaying weired characters in place of accented characters

    function remove_accents($str, $charset='utf-8')
    {
        $str = htmlentities($str, ENT_NOQUOTES, $charset);
    
        $str = preg_replace('#\&amp;([A-za-z])(?:acute|cedil|circ|grave|ring|tilde|uml)\;#', '\1', $str);
        $str = preg_replace('#\&amp;([A-za-z]{2})(?:lig)\;#', '\1', $str);
        $str = preg_replace('#\&amp;[^;]+\;#', '', $str);
    
        return $str;
    }
    
  3. Processing data and sending the email:

    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

Define file input for each attachment with:

<input name="upload[]" type="file"/>
Fares M.
  • 1,538
  • 1
  • 17
  • 18
  • Hi, thanks for your answer but multiple attribute do not support IE7,8,9 – devdarsh May 25 '14 at 15:37
  • Also i cannot allow multiple selections thro' a single input – devdarsh May 25 '14 at 15:38
  • You can with recent browsers, but if you want make all your file inputs with the same name like this `` and you'll get all your attachments in the same array on server side, i already made a script that works great, it can send multiple attachments with additional informations like: _sender mail, receiver mail, subject and a message on the body of the mail_, if you're not in hurry, tomorrow i'll post for you some useful snippets from my script, sorry, today i can't – Fares M. May 25 '14 at 17:33
  • Thanks Fares. I will give it a try Looking forward your useful snippets. No hurry. Take your time. – devdarsh May 26 '14 at 06:20
  • @devdarsh I updated my answer, if you've some questions about code or logic, you're welcome, i'll try to make clear for you. – Fares M. May 27 '14 at 14:00