Solved

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

Posted on 2011-02-17
18
352 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
  • 8
  • 5
  • 4
  • +1
18 Comments
 
LVL 38

Expert Comment

by:Aaron Tomosky
Comment Utility
Phpmailer.
0
 
LVL 11

Accepted Solution

by:
VanHackman earned 250 total points
Comment Utility
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
Comment Utility
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
 
LVL 13

Assisted Solution

by:darren-w-
darren-w- earned 250 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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-
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 11

Expert Comment

by:VanHackman
Comment Utility

>> 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
Comment Utility
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
Comment Utility
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-
Comment Utility
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-
Comment Utility
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
Comment Utility
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-
Comment Utility
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
Comment Utility
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
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

772 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

11 Experts available now in Live!

Get 1:1 Help Now