Solved

help modify this script to send .CSV file as email attachment on form submit

Posted on 2016-09-03
7
18 Views
Last Modified: 2016-10-24
I have this code working properly to output a .csv file into the browser download queue on form submit, but what I really need it to do is to send the csv file as an email attachment to  a specific email address instead of downloading in browser...

It's been suggested that I just have the csv save on the server and then email a link, but I need the csv attached to the email that gets sent on submit.

If someone can help me with that code, that would be AWESOME!
<?php
if(isset($_POST['submit'])){

    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

    //check name is set
    if($firstName ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //if no errors carry on
    if(!isset($error)){

        # Title of the CSV
        $Content = "firstName, lastName, title, phone, fax, email\n";

        //set the data of the CSV
        $Content .= "$firstName, $lastName, $title, $phone, $fax, $email\n";

        # set the file name and create CSV file
        $FileName = "formdata-".date("d-m-y-h:i:s").".csv";
        header('Content-Type: application/csv'); 
        header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
        echo $Content;
        exit();
    }
}

//if their are errors display them
if(isset($error)){
    foreach($error as $error){
        echo "<p style='color:#ff0000'>$error</p>";
    }
}
?> 

<form action='' method='post'>
<p><label>First Name</label><br><input type='text' name='firstName' value=''></p> 
<p><label>Last Name</label><br><input type='text' name='lastName' value=''></p> 
<p><label>Title</label><br><input type='text' name='title' value=''></p> 
<p><label>Phone</label><br><input type='text' name='phone' value=''></p> 
<p><label>Fax</label><br><input type='text' name='fax' value=''></p> 
<p><label>Email</label><br><input type='text' name='email' value=''></p> 
<p><input type='submit' name='submit' value='Submit'></p> 
</form>

Open in new window

0
Comment
Question by:dvointeractive
  • 3
7 Comments
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 350 total points (awarded by participants)
ID: 41783002
This seems to be a duplicate of this question https://www.experts-exchange.com/questions/28966234/help-modify-this-script-to-send-CSV-file-as-email-attachment-on-form-submit.html

In that question I posted links to PHPMailer which is a code solution to the problem. It is very easy to use and if you scroll down on that link there is a comprehensive example on how to use it.
From that page

1. Include the PHPMailer class
require 'PHPMailerAutoload.php';

Open in new window


2. Create a new instance of PHPMailer
$mail = new PHPMailer;

Open in new window


3. If you need to specify SMTP logon credentials then refer to that page on how to do that - most ISP's you can just do a standard send.

4. Set your sender
$mail->setFrom('from@example.com', 'Mailer');

Open in new window


5. Add your recipients
$mail->addAddress('joe@example.net', 'Joe User');
$mail->addAddress('ellen@example.com');

Open in new window


6. Set your supply to
$mail->addReplyTo('info@example.com', 'Information');

Open in new window


7. Add attachment
$mail->addAttachment('/var/tmp/myfile.csv');

Open in new window


8. If this is an HTML message then set that
$mail->isHTML(true);  

Open in new window


9. Set subject, body and alt body (latter is the text equivalents, useful for getting SPAM score down)
$mail->Subject = 'Here is the subject';
$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

Open in new window


10. Send and error check
if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

Open in new window


It is literally that simple - all you need is in the link I posted in the "Simple Example"
0
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 350 total points (awarded by participants)
ID: 41783007
Your CSV is generated as a string - not a file so you need to use AddStringAttachment. I have put some demo code based on your code below. You will need to amend email's etc
I have put the changes between comments including the require - typically require goes to the top of the file so move it after code is working, I put it there so all changes are in one place.
<?php
if(isset($_POST['submit'])){

    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

    //check name is set
    if($firstName ==''){
        $error[] = 'Name is required';
    }

    //check for a valid email address
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
         $error[] = 'Please enter a valid email address';
    }

    //if no errors carry on
    if(!isset($error)){

        # Title of the CSV
        $Content = "firstName, lastName, title, phone, fax, email\n";

        //set the data of the CSV
        $Content .= "$firstName, $lastName, $title, $phone, $fax, $email\n";

        # set the file name and create CSV file
        $FileName = "formdata-".date("d-m-y-h:i:s").".csv";
		
		// ** ADDED MAIL CODE
		// ATTACHMENT FROM STRING INSTEAD OF A FILE
		// require usually goes at the top of the file 
		// I have put it here to group the changes
		
		require 'PHPMailerAutoload.php';
		$mail = new PHPMailer;
		$mail->setFrom('web@dvointeractive.com', 'Mailer');
		$mail->addAddress('someone@somewhere.net', 'Joe User');
		$mail->AddStringAttachment($Content,$FileName);
		$mail->isHTML(true); 
		$mail->Subject = 'Here is the subject';
		$mail->Body    = 'This is the HTML message body <b>in bold!</b>';
		$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
		if(!$mail->send()) {
			echo 'Message could not be sent.';
			echo 'Mailer Error: ' . $mail->ErrorInfo;
		} else {
			echo 'Message has been sent';
		}
		// END ADDITION
		
        header('Content-Type: application/csv'); 
        header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
        echo $Content;
        exit();
    }
}

//if their are errors display them
if(isset($error)){
    foreach($error as $error){
        echo "<p style='color:#ff0000'>$error</p>";
    }
}
?> 

<form action='' method='post'>
<p><label>First Name</label><br><input type='text' name='firstName' value=''></p> 
<p><label>Last Name</label><br><input type='text' name='lastName' value=''></p> 
<p><label>Title</label><br><input type='text' name='title' value=''></p> 
<p><label>Phone</label><br><input type='text' name='phone' value=''></p> 
<p><label>Fax</label><br><input type='text' name='fax' value=''></p> 
<p><label>Email</label><br><input type='text' name='email' value=''></p> 
<p><input type='submit' name='submit' value='Submit'></p> 
</form>

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 150 total points (awarded by participants)
ID: 41783256
No points for this please, but this construct seems to be something that a lot of novice PHP programmers keep copying over and over without understanding that it's meaningless drivel with potentially dangerous consequences.  Really.  Please don't do this.
    //collect form data
    $firstName = $_POST['firstName'];
    $lastName = $_POST['lastName'];
    $title = $_POST['title'];
    $phone = $_POST['phone'];
    $fax = $_POST['fax'];
    $email = $_POST['email'];

Open in new window

Instead of copying the request variable into $firstName, just use $_POST['firstName'].  That way your colleagues (or you, it it's been more than a few days) can see that you used dangerous and unfiltered external data in your script!

If this sounds to you like there may be something wrong about copying request variables without filtering them, you're on the right track!  Maybe learn about "accept only known good values" (Google the phrase).
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41847885
I think that a couple of comments in this thread addressed the question
1

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses four methods for overlaying images in a container on a web page
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now