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

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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<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  = "me@domain.com"; // 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

  • 4
  • 3
1 Solution

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

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);
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

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.
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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now