Solved

Adding an attachment to an email sent from a web form in PHP

Posted on 2011-02-17
18
363 Views
Last Modified: 2012-05-11
Im uisng the following code that picks up data from a web form. Now I just need to add code to attach the file. what is the best way to do this?

<?php
/* Subject and Email Variables */
	$EmailSubject = 'Member Application';
	$EmailTo = 'Mail@My.com.au';
	
/* Get Data Variables */

	$GivenName = $_POST['Given_Name'];
	$FamilyName = $_POST['Family_Name'];
	$ImageFile = $_POST['Image_File'];
	$EmailAddress = $_POST['Email_Address'];
	
	$Body = <<<EOD
<br><hr><br>
Email: $email <br>
Given_Name: $GivenName <br>
Family_Name: $FamilyName <br>
Image_File: $ImageFile <br>
Email_Address: $EmailAddress <br>
EOD;

	$headers = "From: $EmailAddress\r\n";
	$headers .= "Content=type: text/html\r\n";
	$success = mail($EmailTo, $EmailSubject, $Body, $headers);

?>

Open in new window

0
Comment
Question by:kentgorrell
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 4
  • +1
18 Comments
 
LVL 39

Expert Comment

by:Aaron Tomosky
ID: 34923493
Phpmailer.
0
 
LVL 11

Accepted Solution

by:
VanHackman earned 250 total points
ID: 34923514
As, aarontomosky suggested, PhpMailer is the easiest (and probably the better?...) option here.

I have attached a example about how to use it to send e-mail which attached files.
As you will see it's very easy.

Just edit the index.php page with the right data.

Let me know if it helped you.

Kind regards,
VanHackman.
PhpMailerExample-VanHackman.zip
0
 

Author Comment

by:kentgorrell
ID: 34923644
It looks like the web form gets a variable of the file not just it's name so Image_File isn't a string. But the form doesn't seem to be uploading the file. I need to resolve that first.

I'll post a separate question for that and get back to you.

0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 13

Assisted Solution

by:darren-w-
darren-w- earned 250 total points
ID: 34924548
Here is an example of uploading an attachment:

http://www.tizag.com/phpT/fileupload.php

the details about the file are held in $_FILE global var

Some more info here:

http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment



0
 

Author Comment

by:kentgorrell
ID: 34930486
Just so I understand what is going on.

In the HTML form the line
<input type="file" name="Image_File" id="Image_File" />
Diplays the file name but does not actually upload the file?

When does the file get uploaded?

What type of variable is "Image_File"? It doesn't seem to be a string. this line fails
$ImageFile = $_POST['Image_File'];
I assume because the file should be in a files array?
0
 
LVL 11

Expert Comment

by:VanHackman
ID: 34930512
Do not forget to set you enctype to: enctype="multipart/form-data"....

Take a look:

http://www.w3schools.com/PHP/php_file_upload.asp


0
 
LVL 11

Expert Comment

by:VanHackman
ID: 34930520
And yes... you should look for the image into the $_FILES array...

$_FILES["Image_File"]["name"] = the image name.
$_FILES["Image_File"]["tmp_name"] = the temp. path to the image....
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 34930542
The file only gets uploaded when you press the submitt button.
To reference the image file you use the file var above.
If you print_r on the var it will echo what values the array holds, this will be things like the file size, tempory file name, uploaded filename etc
0
 

Author Comment

by:kentgorrell
ID: 34931442
That's great, thankyou Darren-W and VanHackman, I now have a better understanding of what's happening.

And now I can send the original image name in the email body (I will need to rename it but that's another story) and get its temp name. I notice the temp name doesn't have a file extension. Is this normal?

I'm also guessing the temp file (and folder) is deleted when the script teminates.

So how do I attach the file to the email? do I need to use chunk_split and/or base64_encode and if so how?

I'll probably use the PHPMailer in the future, thanks for code VanHackman, but for this one I'd like to use the script I already have and have spent hours tested.
0
 
LVL 11

Expert Comment

by:VanHackman
ID: 34931486

>> I notice the temp name doesn't have a file extension. Is this normal?

No, it should have full path to the file.

>> I'm also guessing the temp file (and folder) is deleted when the script teminates.

Yes, in most of the servers it's cleaned by default.

>> So how do I attach the file to the email? do I need to use chunk_split and/or base64_encode and if so how?

If you want to do it "manually" yes... you should encode it using base64. and also set a "boundary"

It will be something like:

$attachment = chunk_split(base64_encode(file_get_contents("yourfile.zip")));

But here is a functional example that you could check:

http://www.geekology.co.za/blog/2009/06/sending-emails-with-attachments-using-php-mail-function/
0
 

Author Comment

by:kentgorrell
ID: 34931546
so these lines should get the temp file as the attachment.
$TempFile = $_FILES["Image_File"]["tmp_name"];
$attachment = chunk_split(base64_encode(file_get_contents($TempFile)));

I got lost in the example in the link but it looks like I then append this to the text I already have in $Output then mail it

$Output .= $attachment;

mail($to, $subject, $output, $headers);

or is there anything else I need to do when appending $attachment to $Output?





$TempFile = $_FILES["Image_File"]["tmp_name"];
$attachment = chunk_split(base64_encode(file_get_contents($TempFile)));

$Output .= $attachment;

mail($to, $subject, $output, $headers);

Open in new window

0
 

Author Comment

by:kentgorrell
ID: 34931905
I've tried to use the phpmailer class but get this error

Warning: require(file:/class.phpmailer.php) [function.require]: failed to open stream: No such file or directory in /clientdata/zeus-dynamic-1/o/s/My.com.au/www/MailFormData.php on line 2

Fatal error: require() [function.require]: Failed opening required 'file:/class.phpmailer.php' (include_path='.:/clientdata/php/php5/lib/php:/clientdata/php/lib') in /clientdata/zeus-dynamic-1/o/s/My.com.au/www/MailFormData.php on line 2

I have class.phpmailer.php in the root directory along wtih the php ifle calling it.
is this where it should be?
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 34932752
So how do I attach the file to the email

Their is an example of a of using an attachment on the php mail manual page

look at 'akam 28-May-2008 01:55' on this page

http://php.net/manual/en/function.mail.php

will take a look at the php mailer problem soon how are you implementing it in your code?
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 34933065
Hi,

I've mocked together your original example with php mailer,

<?php

/* Subject and Email Variables */
$EmailSubject = 'Member Application';
$EmailTo = 'Mail@My.com.au';

/* Get Data Variables */

$GivenName = $_POST['Given_Name'];
$FamilyName = $_POST['Family_Name'];
$ImageFile = $_POST['Image_File'];
$EmailAddress = $_POST['Email_Address'];


//fill values as if sent  for testing

$GivenName = "Bob";
$FamilyName = "Jones";
$ImageFile = "test_document.txt";
$EmailAddress = "";  //from email address goes here **** add for testing
$EmailTo = ""; //to email address goes here *** add for testing


$Body = <<<EOD
<br><hr><br>
Email: $email <br>
Given_Name: $GivenName <br>
Family_Name: $FamilyName <br>
Image_File: $ImageFile <br>
Email_Address: $EmailAddress <br>
EOD;

//$headers = "From: $EmailAddress\r\n";
//$headers .= "Content=type: text/html\r\n";
//$success = mail($EmailTo, $EmailSubject, $Body, $headers);
?>
<?php

require("class.phpmailer.php");

$mail = new PHPMailer();

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "localhost";  // specify main and backup server
//$mail->SMTPAuth = true;     // turn on SMTP authentication
//$mail->Username = "jswan";  // SMTP username
//$mail->Password = "secret"; // SMTP password

$mail->From = $EmailAddress;
$mail->FromName = $GivenName . " " . $FamilyName;
$mail->AddAddress($EmailTo);
//$mail->AddAddress("ellen@example.com");                  // name is optional
//$mail->AddReplyTo("info@example.com", "Information");

$mail->WordWrap = 50;                                 // set word wrap to 50 characters
$mail->AddAttachment($ImageFile);         // add attachments
//$mail->AddAttachment("/tmp/image.jpg", "new.jpg");    // optional name
$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = $EmailSubject;
$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. <p>";
   echo "Mailer Error: " . $mail->ErrorInfo;
   exit;
}

echo "Message has been sent";
?>

Open in new window


Some things to note, you should replace $imagefile = to something like '$_FILES["file"]["tmp_name"]', like in the example below, this will pick use the image that has been uploaded by the passing form.


http://www.w3schools.com/php/php_file_upload.asp

I have tested this out on a ubuntu box that has a local mailer, but you may need to change the settings in the file to point to your mail server as required.

Have enclosed the complete working code with the phpmailer class, just extract all the files to a folder on your webserver and call the index file (having adjusted the code)

Darren
WebTestFolder.zip
0
 

Author Comment

by:kentgorrell
ID: 34934569
Thanks Darren, there is some good stuff there. the examples at w3 schools are really good.

but unless PHPMailer is recognised then I can't use it.

as I said in my last post. PHPMailer throws the previously mentioned errors.

the mailing script simply cannot find the PHPMailer Class.

Where does it need to be and does it require some sort of registration?
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 34935178
Has the class file got read rights by the webserver? Assuming that the file is in the same folder as the include file as in my example it should be able to access it.  Create a test php file in the same folder with an echo of text and include that and see if that works.
0
 

Author Comment

by:kentgorrell
ID: 34935554
OK we are there, Thanks very much Darren and VanHackman

Ive used the output buffering method from one of the links Darren posted.
http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php

The class looks good but if I'm going to have problems getting it to run then I'm better of using standard php files.

The temp file had no extension, so I had to get that from the original file name, then copy the temp to a GUID with the file extension appended.

You both deserve full points.

 MailerExample.php
0
 

Author Closing Comment

by:kentgorrell
ID: 34935566
Not an easy question. if phpmailer had worked it may have been an easier answer. Both Darren W and VanHackman put in brilliantly.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Link failure 16 70
SQL querys that gives me from one table into another. 2 41
PHP Curl Problem 10 42
php ajax contact form gives me undefined index error upon submission 2 39
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

726 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