php multiple file email attachment

I tried this the other day and what I am trying to do is to get the code that I have working to upload and attach 2 image files in an email.

The server this needs to work on is running PHP4 (can't be changed) I need to find a solution that uses the .html file and the .php file.

I have simplified the form to make it easier to look at and work with. The current file works with a single upload and attachment, but can't figure out how to tweak the code to have 2 different files upload and become attachments in an email.

Please don't post links to read up on possible solutions. I would like help with the code I am including to find a solution.

I am pretty new to php, so the solution has been a little out of my reach. Thank you in advance.
- - - - - - - - HTML DOCUMENT - - - - - - - - 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<form action="upload.php" method="post" enctype="multipart/form-data">
<table cellpadding="6" cellspacing="0" border="0">
		<td valign="top"><input size="45" type="text" name="Email" class="textfield"></td>
        <td valign="top"><label>Email Address</label></td>
	    <td valign="top"><textarea name="Statement" class="textfield" rows="6" cols="43" /></textarea></td>
        <td valign="top"><label>Statement/Description (about 50 words)</label></td>
		<td valign="top" colspan="2"><hr></td>
		<td valign="top" align="right"><input type="file" name="userfile" id="file"></td>
        <td valign="top"><label>Upload Logo</label></td>
		<td valign="top" align="right"><input type="file" name="userfile2" id="file2"></td>
        <td valign="top"><label>Upload Image</label></td>
		<td valign="top" colspan=""><hr></td>
		<td valign="top"><label>&nbsp;</label></td>
        <td valign="top"><input type="submit" value="Submit File" /></td>


 - - - - - - - - PHP DOCUMENT - - - - - - - - 

Code to UPLOAD files to 'files' folder
      $allowed_filetypes = array('.jpg','.gif','.tif','.png','.zip'); 
      $max_filesize = 8388608; // Maximum filesize in BYTES (currently 8MB).
      $upload_path = '/httpdocs/test';
		$filename = $_FILES['userfile']['name']; // Get the name of the file (including file extension).
		$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1); // Get the extension from the filename.

		$handle = fopen($_FILES['userfile']['tmp_name'], "rb");
		$filecontents = fread($handle, filesize($_FILES['userfile']['tmp_name']));
   // Check if the filetype is allowed, if not DIE and inform the user.
      die('The file you attempted to upload is not allowed. Please select a .jpg, .gif, .tif or upload from a .zip');
   // Now check the filesize, if it is too large then DIE and inform the user.
   if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
      die('The file you attempted to upload is too large.');
Code to SEND form details to email address
$sendto  = ""; // send to email address
$subject = "Upload";
$email = $_POST["Email"];
$statement =  $_POST["Statement"];
// Build the email body text
$emailcontent = "
Contact Email: $email<br />

Statement/Description:<br />
$headers = "From: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed;";
$headers .= "boundary=$emailid\r\n--".$emailid."\r\n";
$headers .= "Content-Type: text/html; charset=\"iso-8859-1\"\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n".$emailcontent."\r\n--".$emailid."\r\n";
$headers .="Content-Type: ".$_FILES['userfile']['type']."; name=\"".$filename."\"\r\n";
$headers .="Content-Transfer-Encoding: base64\r\n";
$headers .="Content-Disposition: attachment; filename=\"$filename\"\r\n\r\n".chunk_split(base64_encode($filecontents))."\r\n--".$emailid."--";
$success = mail($sendto, $subject, $emailcontent, $headers);

		if ($success){
		  print "<meta http-equiv=\"refresh\" content=\"0;URL=thank_you.html\">";
		  print "<meta http-equiv=\"refresh\" content=\"0;URL=error.html\">";

Open in new window

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.


i attach a raw code which show how to save uploaded files and then send those files in email.

function "multi_attechment" takes files paremeters with fulladdress (document root) to files in array and send them as email attachments



$subject='Image Files';

$mail_message='<strong>Mail From '.$name.'</strong><br>Name: '.$_POST['name'].'<br>'.$Emsg;
multi_attechment($email,$to,$subject,$mail_message,$files); //FUNCTION WHICH SEND FILES

function multi_attechment($from,$to,$subject='No Subject!!!',$message='No Text!!!',$files=array()) {
	$totle = count($files);
	$file_type ="text/plain";
	$headers ="From: ".$from;

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

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

	$message ="This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-type: text/html; charset=iso-8859-1 \r\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n"; 
	$message .="--{$mime_boundary}\n";
	if($totle!=0) {
			$file = fopen($files[$x],"rb");
			$data = fread($file,filesize($files[$x]));
			$data = chunk_split(base64_encode($data));
			$message .="Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" . 
			"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" . 
			"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
			$message .="--{$mime_boundary}\n";
	if(mail($to, $subject, $message, $headers)) {
		return 'Email sent successfully.';
	} else {
		return 'Sorry, Email not sent.';

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
javahutAuthor Commented:
I loaded this in and changed the email address to check on how it is submitting. The path I used for the files to upload to was,


both images come through, but only one is available. Also, the path on the images sent, which are called image1.gif and image2.jpg that are attached are received as:

First image comes in fine. second one comes in empty. I also, don't see the second image in the upload folder on the server. Are the images suppose to be cleared after the attachments are sent?

Any insight into what is happening on both files not being received.
The second file may not uploaded because the second file field name in your form is "userfile2" and i use "userfile1" on line 10, so  try again with replace the name.

files are not deleted after sending with email. but if you want to delete you can use
if(file_exists($file_path)) unlink($file_path);
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

javahutAuthor Commented:
I had seen that the naming convention had been changed when I received your raw code, so I had changed that on the ul.html file. Also changed the id to file1 to keep consistent with what you named the files.

where should the if(file_exists(  statement go? Not sure were to put that.
"where should the if(file_exists(  statement go? Not sure were to put that."

this code will delete the files so put this code just after
multi_attechment($email,$to,$subject,$mail_message,$files); //FUNCTION WHICH SEND FILES
if(file_exists($file_path)) unlink($file_path);  // Delete files after sending

line this is on line 16 in code
javahutAuthor Commented:
I played with the solution that you sent. Meant to get back to you earlier, but was unable. The code that you had put together was great. The only thing that was hanging everything up the delivery for receiving the 2 attachments was:


The second statement didn't have $file_path1, but once I got a fresh look and changed that, it worked great. I apologize for the length of time this dragged out from initial to resolve. Thank you.
javahutAuthor Commented:
There was a change that needed for the $file_path to declare the 2 files. The solution worked great and is exactly what was needed.

Thank you.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Email Servers

From novice to tech pro — start learning today.