0

I've been searching all day and have not found the code that works. I'm trying, after submitting form,

  1. Validate - This works
  2. Check to see if record exists - This works
  3. Insert record - This works
  4. Attach a CSV that has the form variables - This does not work

This is a scaled down version

<?php 

$to = "[email protected]";


if(isset($_POST['submit'])) 
{ 

// VALIDATION

  if(empty($_POST['address'])) 
  { 

   "First Name Required";

  } 


 if(empty($_POST['email'])) 
  { 

   "Last Name Required"; 

  }


  if(empty($error))  
  { 

    $subject = 'The Form';
    $headers = "MIME-Version: 1.0 \r\n";
    $headers .= "Content-Type: text/html; \r\n" ;
    $headers .= "From: [email protected]\r\n"."Reply-to: {$_POST['email']}\r\n"; 


   $msg .="<html>
    <head></head>
    <body>
    <table>
    <tr><td>
        <table>
           <tr><td>This is the email sent.</td></tr>
        </table>
      </body>
    </html>";


     include('con.php');

     $con = mysqli_connect($host,$user,$pass,$dbName);
     if (!$con)
      {
      die('Could not connect: ' . mysqli_error($con));
      }

      mysqli_select_db($con,"thetable");


    $email= mysqli_real_escape_string($con, $_POST['email']);
    $address= mysqli_real_escape_string($con, $_POST['address']);

    $sql = "SELECT * FROM thetable WHERE `email` = '{$email}' OR `address` = '{$address}'";
    $result = mysqli_query($con,$sql);

    if(($result->num_rows)>= 1)
    {
    $theerror = "You exist"; 
    }

    else
       {
$sql="INSERT INTO thetable(email, address) VALUES ('$_POST[email]','$_POST[address]'";

    $success = "Sent ... Insert it!!!"; 


          if (!mysqli_query($con,$sql))
          {
          die('Error: ' . mysqli_error($con));
          }

             //The Attachment

            $cr = "\n";
            $data = "Email" . ',' . "address" . ',' . $cr;
            $data .= "$email" . ',' . "$address" . $cr;
            $fp = fopen('diploma_apprenticeship_form_sub.csv','a');
            fwrite($fp,$data);
            fclose($fp);

            $attachments[] = Array(
               'data' => $data,
               'name' => 'diploma_apprenticeship_form_sub.csv',
               'type' => 'application/vnd.ms-excel'
            );


            //Generate a boundary string

            $semi_rand = md5(time());
            $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";


            //Add the headers for a file attachment


            $headers = "MIME-Version: 1.0\n" .
                       "From: {$from}\n" .
                       "Content-Type: multipart/mixed;\n" .
                       " boundary=\"{$mime_boundary}\"";


            //Add a multipart boundary above the plain message


            $msg= "This is a multi-part message in MIME format.\n\n" .
                      "--{$mime_boundary}\n" .
                      "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
                      "Content-Transfer-Encoding: 7bit\n\n" .
                      $text . "\n\n";


            //Add sttachments

            foreach($attachments as $attachment){
               $data = chunk_split(base64_encode($attachment['data']));
               $name = $attachment['name'];
               $type = $attachment['type'];

               $msg.= "--{$mime_boundary}\n" .
                          "Content-Type: {$type};\n" .
                          " name=\"{$name}\"\n" .
                          "Content-Transfer-Encoding: base64\n\n" .
                          $data . "\n\n" ;
            }

            $msg.= "--{$mime_boundary}--\n";

           $result = @mail($to, $subject, $msg, $headers); 
        }


       mysqli_close($con);


      { 

      } 
    } 
  } 

?>
16
  • 1
    Why won't you use any normal class, like, for example, phpmailer, for attachments and email?? Commented Oct 28, 2014 at 0:47
  • Because it would take hours and hours to make those changes. All I want it to attach a csv have any ideas? Commented Oct 28, 2014 at 0:56
  • 1
    You already spent more time trying to create mail from the scratch. And you'll spend more time trying to find a problem (at least the source of the generated email should be shown for that). Trust me, phpmailer will do it much faster and shorter. Commented Oct 28, 2014 at 0:57
  • phpmailer doesn't have the advanced validation as I have so I don't like it. Note the validation is scaled down in the code you see here. Can anyone out there help? Commented Oct 28, 2014 at 1:02
  • 1
    @motocrz What doesn't work? I'd can the attitude, and look at my answer. Trust me it's not as hard as you are making it. Commented Oct 28, 2014 at 1:50

1 Answer 1

1

Try this,

$f = fopen('path to file', 'w'); //path such as __DIR__./file.csv';  write mode.

fputcsv( $f, $data);
//data is an array of data ie array('one', 'two'); is one,two in the file ~ make a loop
//around this and write as many lines as you need, like array(header, header1); then
//array(data, data1) etc...

fclose($f); //close the file when done

http://phpmailer.worxware.com/

 require 'PHPMailerAutoload.php';

 $mail = new PHPMailer;
 $mail->From = '[email protected]';
 $mail->addAddress('[email protected]', 'Joe User');
 $mail->addAttachment( __DIR__.'/file.csv');  
 $mail->Subject = 'Here is the subject';
 $mail->Body    = 'This is the HTML message body <b>in bold!</b>';

 $mail->send();

 unlink( __DIR__.'/file.csv' ); //remove the file

Oh and get rid of all that header stuff, let php mailer do its job, which as you mentioned is not to validate your data. Work up a process flow.

Input Validate Calculate ( assign values ) Output ( send your email ) Clean up ( remove any files, etc.. )

etc..

AS An update

$msg .="<html>
<head></head>
<body>
<table>
<tr><td>
    <table>
       <tr><td>This is the email sent.</td></tr>
    </table>
  </body>
</html>";

... and then latter

$msg= "This is a multi-part message in MIME format.\n\n" .
                  "--{$mime_boundary}\n" .
                  "Content-Type: text/html; charset=\"iso-8859-1\"\n" .
                  "Content-Transfer-Encoding: 7bit\n\n" .
                  $text . "\n\n";

Also your likely to get a warning for the first message as you are not defining the variable before using the concant on it.

 $msg .= 'something';

Should be

  $msg = 'something';

Or

  $msg = '';
  $msg .= 'something';
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks ArtisticPhoenix "MIME-Version: 1.0 \r\n", "MIME-Version: 1.0\n" fixed it. I noticed when I copied and paste his suggestion I accidentally copied the double quote. It's working now without phpmailer.
I'd still use php mailer, different severs will have different header requirements. but it's your choice.
I'll change it later to phpmailer. Can you tell me why I only get the attachment and not the email? I was so happy to see the attachment that the actual email body isn't there.
Its because you are reassigning the $msg variable.
Right so I named it to $msgemail but got code only in the email.. sorry forgot to mention that.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.