• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 392
  • Last Modified:

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

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
kentgorrell
Asked:
kentgorrell
  • 8
  • 5
  • 4
  • +1
2 Solutions
 
Aaron TomoskySD-WAN SimplifiedCommented:
Phpmailer.
0
 
VanHackmanCommented:
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
 
kentgorrellAuthor Commented:
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
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
darren-w-Commented:
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
 
kentgorrellAuthor Commented:
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
 
VanHackmanCommented:
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
 
VanHackmanCommented:
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
 
darren-w-Commented:
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
 
kentgorrellAuthor Commented:
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
 
VanHackmanCommented:

>> 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
 
kentgorrellAuthor Commented:
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
 
kentgorrellAuthor Commented:
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
 
darren-w-Commented:
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
 
darren-w-Commented:
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
 
kentgorrellAuthor Commented:
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
 
darren-w-Commented:
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
 
kentgorrellAuthor Commented:
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
 
kentgorrellAuthor Commented:
Not an easy question. if phpmailer had worked it may have been an easier answer. Both Darren W and VanHackman put in brilliantly.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

  • 8
  • 5
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now