title: How to send an email with a CSV attachment from a string
body: <p>Here is my attempt at it can you let me know what I am doing wrong?</p>
  
  <p>allputcsv converts the array into a csv formatted string. That is then base64 encoded and chunk split, this seems to work for normal files but is there something different I should do because I am using a string?</p>
  
  <pre><code>&lt;?php
  
  function sputcsv($row, $delimiter = ',', $enclosure = '"', $eol = "\n")
  {
      static $fp = false;
      if ($fp === false)
      {
          $fp = fopen('php://temp', 'r+');
      }
      else
      {
          rewind($fp);
      }
  
      if (fputcsv($fp, $row, $delimiter, $enclosure) === false)
      {
          return false;
      }
  
      rewind($fp);
      $csv = fgets($fp);
  
      if ($eol != PHP_EOL)
      {
          $csv = substr($csv, 0, (0 - strlen(PHP_EOL))) . $eol;
      }
      return $csv;
  }
  
  function allputcsv($arr) {
      $str = "";
      foreach($arr as $val) {
          $str .= sputcsv($val);
      }
      return $str;
  }
  
  function send_mail($arr) {
      $to = 'youraddress@example.com'; 
      $subject = 'Test email with attachment'; 
      $random_hash = md5(date('r', time())); 
      $headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com"; 
      $headers .= "\r\nContent-Type: multipart/mixed; boundary=\"--".$random_hash."\""; 
      $attachment = chunk_split(base64_encode(allputcsv($arr))); 
      ob_start();
      ?&gt; 
      --&lt;?php echo $random_hash; ?&gt;  
      Content-Type: text/plain; charset=ISO-8859-1; format=flowed
      Content-Transfer-Encoding: 7bit
  
      Hello World!!! 
      This is simple text email message. 
  
      --&lt;?php echo $random_hash; ?&gt;  
      Content-Type: application/vnd.ms-excel;
       name="test.csv"
      Content-Transfer-Encoding: base64
      Content-Disposition: attachment;
       filename="test.csv"
  
      &lt;?php echo $attachment; ?&gt; 
      --&lt;?php echo $random_hash; ?&gt;-- 
  
      &lt;?php 
      $message = ob_get_clean(); 
      $mail_sent = @mail( $to, $subject, $message, $headers ); 
  }
  
  $array = array(array(1,2,3,4,5,6,7),array(1,2,3,4,5,6,7),array(1,2,3,4,5,6,7));
  
  send_mail($array);
  ?&gt;
  </code></pre>
  
  <p>Notes: I have to use the mail function I don't have a choice (I could use a wrapper but I would prefer not to) and I cant save the file on the server side.</p>