Jump to content

Trying to get file to attach to email message from upload form


wolfsta

Recommended Posts

Hi all

 

I have a script that I have patched together and got to work in pieces.  I'm up to the last part.  I have the form working and emailing.  It also will upload an image by itself and put it in a folder.  Now i just need to tie those together and have the image put in the email as an attachment then deleted from server.

 

I have it at a stage where it sends me the users details.. and it tries to send the photo but it comes through as junk txt.  I think its the MIME encoding stuff that I have wrong.. not sure?

 

Here's what I have so far.

 


$attachment = $path_of_uploaded_file;
$fileatt = $attachment; // Path to the file                  
$fileatt_type = "application/octet-stream"; // File Type 
    $start=	strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment 

    $file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$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}\""; 

$email_message .= "This is a multi-part message in MIME format.\n\n" . 
                "--{$mime_boundary}\n" . 
                "Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
               "Content-Transfer-Encoding: 7bit\n\n" . 

 $data = chunk_split(base64_encode($data)); 
$email_message .= "--{$mime_boundary}\n" . 
                  "Content-Type: {$fileatt_type};\n" . 
                  " name=\"{$fileatt_name}\"\n" . 
                  "Content-Disposition: attachment;\n" . 
                  " filename=\"{$fileatt_name}\"\n" . 
                  "Content-Transfer-Encoding: base64\n\n" .
                 $data . "\n\n" . 
                  "--{$mime_boundary}--\n";
     
// create email headers
$headers .= 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);  

 

Thanks

 

Wolfsta

Link to comment
Share on other sites

Entire php if you need to look at it. I know its probably quite messy or better ways to do it but I'm a novice, ill tidy up as I go and learn:

 


<?php
if(isset($_POST['email'])) {
     
    // EDIT THE 2 LINES BELOW AS REQUIRED
    $email_to = "asdfasd@adskfjh.com";
    $email_subject = "asdf asdfasdf Application Form";
     
     
    function died($error) {
        // your error code can go here
        ?>
            
		<title>asdfas asdf</title>
		<style type="text/css">
		body {
			background-color: #000;
			text-align: center;
		}
		body,td,th {
			color: #FFF;
			font-family: Arial, Helvetica, sans-serif;
			font-size: 24px;
		}
		</style>
		</head>
		<body link="#FFFFFF" onLoad="setTimeout('history.back()',10000)">
		<p><img src="../images/logo.png" width="326" height="144" alt="asdfadsf" longdesc="http://www.adsfasdf.com" /><br />
		</p>
            <br />
		<p>We are very sorry, but there were error(s) found with the form you submitted.</p>
          	
            <p>Please fix the following errors:</p>
            <hr />
            <br />
            <?php
		echo $error;
		?>
            
            <hr />
            <br />
            
		<p>Click back to fix your error(s) or you will be taken back to the form automatically in 10 seconds...</p>
		<h6> </h6>
		<h6>© asdfasdf 2012</h6>
		</body>
		</html>
            
            <?php
        die();
    }
     
    // validation expected data exists
/*   if(!isset($_POST['first_name']) ||
        !isset($_POST['last_name']) ||
        !isset($_POST['email']) ||
        !isset($_POST['telephone']) ||
        !isset($_POST['comments'])) {
        died('We are sorry, but there appears to be a problem with the form you submitted.');       
    }
     */
    $first_name = $_POST['first_name']; // required
    $last_name = $_POST['last_name']; // required
    $email_from = $_POST['email']; // required
    $telephone = $_POST['telephone']; // not required
    $comments = $_POST['comments']; // required
    $age = $_POST['age'];
$city = $_POST['city'];
$state = $_POST['state'];
$height_feet = $_POST['height_feet'];
    $height_inches = $_POST['height_inches'];


//Get the uploaded file information
$name_of_uploaded_file =
    basename($_FILES['uploaded_file']['name']);
//get the file extension of the file
$type_of_uploaded_file =
    substr($name_of_uploaded_file,
    strrpos($name_of_uploaded_file, '.') + 1);
$size_of_uploaded_file =
    $_FILES["uploaded_file"]["size"]/1024;//size in KBs

//Settings
$max_allowed_file_size = 500000; // size in KB
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "png");
//Validations
if($size_of_uploaded_file > $max_allowed_file_size )
{
  $errors .= "\n Size of file should be less than $max_allowed_file_size";
}
//------ Validate the file extension -----
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++)
{
  if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
  {
    $allowed_ext = true;
  }
}
if(!$allowed_ext)
{
  $errors .= "\n The uploaded file is not supported file type. ".
  " Only the following file types are supported: ".implode(',',$allowed_extensions);
}

//copy the temp. uploaded file to uploads folder
$upload_folder = "../uploads/";
$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;
$tmp_path = $_FILES["uploaded_file"]["tmp_name"];
if(is_uploaded_file($tmp_path))
{
  if(!copy($tmp_path,$path_of_uploaded_file))
  {
    $errors .= '\n error while copying the uploaded file';
  }
}



    $error_message = "";
$string_exp = "/^[A-Za-z .'-]+$/";
  if(!preg_match($string_exp,$first_name)) {
    $error_message .= 'First Name: This is not a valid name.<br /><br />';
  }
  if(!preg_match($string_exp,$last_name)) {
    $error_message .= 'Last Name: This is not a valid last name.<br /><br />';
  }
    $age_exp = "/^(1[89]|[2-9][0-9])$/";
  if(!preg_match($age_exp,$age)) {
    $error_message .= 'Age:  You need to be at least 18+ to apply.<br /><br />';
  }
    $phone_exp = "/^(?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4}$/";
  if(!preg_match($phone_exp,$telephone)) {
    $error_message .= 'Phone: eg 646 555 1234 or 646-555-1234 or (646) 555 1234<br /><br />';
  }
    $email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
  if(!preg_match($email_exp,$email_from)) {
    $error_message .= 'Email: Your address is not invalid eg yourname@emaildomain.com<br /><br />';
  }
  if(strlen($comments) < 2) {
    $error_message .= 'Comments: Please leave a breif message explaining your interest and if you have any previous experience etc.<br /><br />';
  }
  if(strlen($error_message) > 0) {
    died($error_message);
  }
    $email_message = "Form details below:\n\n";
     
    function clean_string($string) {
      $bad = array("content-type","bcc:","to:","cc:","href");
      return str_replace($bad,"",$string);
    }
     
    $email_message .= "First Name:"."\t".clean_string($first_name)."\n";
    $email_message .= "Last Name:"."\t".clean_string($last_name)."\n";
$email_message .= "Age:"."\t".clean_string($age)."\n";
$email_message .= "Height:"."\t".clean_string($height_feet).'ft ' . clean_string($height_inches).'in'."\n";
$email_message .= "City:"."\t".clean_string($city)."\n";
$email_message .= "State:"."\t".clean_string($state)."\n";
    $email_message .= "Email:"."\t".clean_string($email_from)."\n";
    $email_message .= "Telephone:"."\t".clean_string($telephone)."\n";
    $email_message .= "Comments:"."\t".clean_string($comments)."\n";


$attachment = $path_of_uploaded_file;
$fileatt = $attachment; // Path to the file                  
$fileatt_type = "application/octet-stream"; // File Type 
    $start=	strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment 

    $file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$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}\""; 

$email_message .= "This is a multi-part message in MIME format.\n\n" . 
                "--{$mime_boundary}\n" . 
                "Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
               "Content-Transfer-Encoding: 7bit\n\n" . 

 $data = chunk_split(base64_encode($data)); 
$email_message .= "--{$mime_boundary}\n" . 
                  "Content-Type: {$fileatt_type};\n" . 
                  " name=\"{$fileatt_name}\"\n" . 
                  "Content-Disposition: attachment;\n" . 
                  " filename=\"{$fileatt_name}\"\n" . 
                  "Content-Transfer-Encoding: base64\n\n" .
                 $data . "\n\n" . 
                  "--{$mime_boundary}--\n";
     
// create email headers
$headers .= 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);  
?>

<!-- include your own success html here -->

<title>adsfadsf adsfadsf</title>
<style type="text/css">
body {
background-color: #000;
text-align: center;
}
body,td,th {
color: #FFF;
font-family: Arial, Helvetica, sans-serif;
font-size: 24px;
}
</style>
</head>

<body link="#FFFFFF" onLoad="setTimeout('history.back()',10000)">
<p><img src="../images/logo.png" width="326" height="144" alt="asdfasdf" longdesc="http://www.asdfasdf.com" /><br />
</p>
<p>Thank your for applying to asdfadsf asdfadsf.  We will be in touch with you very soon.</p>
<p>You will be redirected back to the site in 10 seconds...</p>
<h6> </h6>
<h6>© asdfasdf 2012</h6>
</body>
</html>

<?php
}
?>

Link to comment
Share on other sites

I just had to do this earlier today.  This is what worked for me.  This works for multiple files.

Mike

 

		if(isset($_FILES['uploadFiles']['name'])) {
		foreach ($_FILES['uploadFiles']['name'] as $i => $name) {
			if ($_FILES['uploadFiles']['error'][$i] == 4) {
				continue; 
			}
			if ($_FILES['uploadFiles']['error'][$i] == 0) {

				if ($_FILES['uploadFiles']['size'][$i] > 99439443) {
					$messages[] = "$name exceeded file limit.";
					continue;  
				}
				if(move_uploaded_file($_FILES['uploadFiles']['tmp_name'][$i], "uploads/$name")) {
					$uploaded++;
					$files[] = "uploads/$name";
				} else {
					echo "Could not upload $name to be attached!<br />";
				}

			}
		}

		//$files = $_FILES['uploadFiles']['tmp_name'];
	}
	echo "$uploaded receipt";
	if($uploaded != 1) {
		echo "s";
	}
	echo " uploaded.";
	foreach ($messages as $error) {
		echo $error;
	}

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

	// headers for attachment
	$eol = PHP_EOL;
	$headers = "From: ".$to.$eol;
	$headers .= "Reply-To: ".$to.$eol;
	$subject = "Expense Report - Period Ending $reportDate";
	$headers .= $eol."MIME-Version: 1.0".$eol; 
	$headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;


	// no more headers after this, we start the body! //

	//$body = "--".$mime_boundary.$eol;
	//$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
	$body .= "This is a multi-part message in MIME format.".$eol;

	// message
	$body .= "--".$mime_boundary.$eol;
	$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
	$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
	$body .= $message.$eol.$eol;

	if($uploaded > 0) {  // if there are attachments add this line to the message, otherwise with no attachments this line will add an unwanted attachment
		//$body .= "--{$mime_boundary}\n";
	}

	if(isset($_FILES['uploadFiles']['name'])) {
		// preparing attachments
		for($x=0;$x<count($files);$x++){
			$file = fopen($files[$x],"rb");
			$data = fread($file,filesize($files[$x]));
			fclose($file);
			$data = chunk_split(base64_encode($data));
			$name = $_FILES['uploadFiles']['name'][$x];
			/*$body .= "–{$mime_boundary}\n";
			$body .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" . 
			"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" . 
			"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
			//$body .="--{$mime_boundary}--\n";
			if ($x==count($files)-1) {
				//$message .="--{$mime_boundary}-\n";
			}
			else{
				//$message .="--{$mime_boundary}\n";
			}*/
			// attachment
			$body .= "--".$mime_boundary.$eol;
			$body .= "Content-Type: application/octet-stream; name=\"".$name."\"".$eol; 
			$body .= "Content-Transfer-Encoding: base64".$eol;
			$body .= "Content-Disposition: attachment".$eol.$eol;
			$body .= $data.$eol.$eol;


		}
		$body .= "--".$mime_boundary."--";
	}

	// send
	$ok = @mail($to, $subject, $body, $headers); 
	if ($ok) { 
		echo "<p>Email sent to $to!</p>"; 
		} else { 
		echo "<p>Email could not be sent!</p>"; 
	}
}

Link to comment
Share on other sites

Mike I tried to use your script but I cant get it to work at all.  I deleted all my code and just used yours and added my email address to the variable $to and it doesn't work.  Changed the name= in my html form to uploadedFiles... I get the email but no attachment at all

 

Any suggestions?

Link to comment
Share on other sites

this is all i did:

 


<?php

$to = 'wolfsta@domain.com';

if(isset($_FILES['uploadFiles']['name'])) {
		foreach ($_FILES['uploadFiles']['name'] as $i => $name) {
			if ($_FILES['uploadFiles']['error'][$i] == 4) {
				continue; 
			}
			if ($_FILES['uploadFiles']['error'][$i] == 0) {

				if ($_FILES['uploadFiles']['size'][$i] > 99439443) {
					$messages[] = "$name exceeded file limit.";
					continue;  
				}
				if(move_uploaded_file($_FILES['uploadFiles']['tmp_name'][$i], "../uploads/$name")) {
					$uploaded++;
					$files[] = "../uploads/$name";
				} else {
					echo "Could not upload $name to be attached!<br />";
				}

			}
		}

		//$files = $_FILES['uploadFiles']['tmp_name'];
	}
	echo "$uploaded receipt";
	if($uploaded != 1) {
		echo "s";
	}
	echo " uploaded.";
	foreach ($messages as $error) {
		echo $error;
	}



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

	// headers for attachment
	$eol = PHP_EOL;
	$headers = "From: ".$to.$eol;
	$headers .= "Reply-To: ".$to.$eol;
	$subject = "Expense Report - Period Ending $reportDate";
	$headers .= $eol."MIME-Version: 1.0".$eol; 
	$headers .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"".$eol.$eol;


	// no more headers after this, we start the body! //

	//$body = "--".$mime_boundary.$eol;
	//$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
	$body .= "This is a multi-part message in MIME format.".$eol;

	// message
	$body .= "--".$mime_boundary.$eol;
	$body .= "Content-Type: text/html; charset=\"iso-8859-1\"".$eol;
	$body .= "Content-Transfer-Encoding: 7bit".$eol.$eol;
	$body .= $message.$eol.$eol;

	if($uploaded > 0) {  // if there are attachments add this line to the message, otherwise with no attachments this line will add an unwanted attachment
		//$body .= "--{$mime_boundary}\n";
	}

	if(isset($_FILES['uploadFiles']['name'])) {
		// preparing attachments
		for($x=0;$x<count($files);$x++){
			$file = fopen($files[$x],"rb");
			$data = fread($file,filesize($files[$x]));
			fclose($file);
			$data = chunk_split(base64_encode($data));
			$name = $_FILES['uploadFiles']['name'][$x];
			/*$body .= "–{$mime_boundary}\n";
			$body .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" . 
			"Content-Disposition: attachment;\n" . " filename=\"$name\"\n" . 
			"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
			//$body .="--{$mime_boundary}--\n";
			if ($x==count($files)-1) {
				//$message .="--{$mime_boundary}-\n";
			}
			else{
				//$message .="--{$mime_boundary}\n";
			}*/
			// attachment
			$body .= "--".$mime_boundary.$eol;
			$body .= "Content-Type: application/octet-stream; name=\"".$name."\"".$eol; 
			$body .= "Content-Transfer-Encoding: base64".$eol;
			$body .= "Content-Disposition: attachment".$eol.$eol;
			$body .= $data.$eol.$eol;


		}
		$body .= "--".$mime_boundary."--";
	}

	// send
	$ok = @mail($to, $subject, $body, $headers); 
	if ($ok) { 
		echo "<p>Email sent to $to!</p>"; 
		} else { 
		echo "<p>Email could not be sent!</p>"; 
	}

?>

Link to comment
Share on other sites

my html.. the form bit with photos.

 


</div>
						<label class="message">
							<span class="text-form">Comments:</span>
							<textarea name="comments"></textarea>
						</label>
						<label>
							<span class="text-form2">Attach a photo:</span>
							<input type="file" name="uploadFiles" class="fl" >
						</label>
						<label>
							<span class="text-form2">Attach a photo:</span>
							<input type="file" name="uploadFiles" class="fl"  >
						</label>
                            <label>
							<span class="text-form2">Attach a photo:</span>
							<input type="file" name="uploadFiles" class="fl"  >
						</label>
							<div class="but"><a class="link1 link-color2" data-type="submit" onClick="document.getElementById('form2').submit()">Submit</a></div>
					</fieldset>
				</form>

Link to comment
Share on other sites

Ok so ended up going back to my code.. As it seemed to be closer.. with the help of a friend realized the MIME encoding stuff wasn't quite right.

 

Here is the fixed working code just have to add multiple file support now:

 


   $attachment = $path_of_uploaded_file;
$fileatt = $attachment; // Path to the file                  
$fileatt_type = "application/octet-stream"; // File Type 
    $start=	strrpos($attachment, '/') == -1 ? strrpos($attachment, '//') : strrpos($attachment, '/')+1;
$fileatt_name = substr($attachment, $start, strlen($attachment)); // Filename that will be used for the file as the attachment 

    $file = fopen($fileatt,'rb'); 
$data = fread($file,filesize($fileatt)); 
fclose($file); 

$semi_rand = md5(time()); 
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x"; 
$headers = "MIME-Version: 1.0\n" . 
            "Content-Type: multipart/mixed;\n" . 
            " boundary=\"{$mime_boundary}\""; 

$email_message = "This is a multi-part message in MIME format.\n\n" . 
                "--{$mime_boundary}\n" . 
                "Content-Type:text/html; charset=\"iso-8859-1\"\n" . 
               "Content-Transfer-Encoding: 7bit\n\n" . 
		   
$email_message .= "Form details below:"."<br>"."<br>";		   
$email_message .= "First Name:"."\t".clean_string($first_name). "<br>";
    $email_message .= "Last Name:"."\t".clean_string($last_name)."<br>";
$email_message .= "Age:"."\t".clean_string($age)."<br>";
$email_message .= "Height:"."\t".clean_string($height_feet).'ft ' . clean_string($height_inches).'in'."<br>";
$email_message .= "City:"."\t".clean_string($city)."<br>";
$email_message .= "State:"."\t".clean_string($state)."<br>";
    $email_message .= "Email:"."\t".clean_string($email_from)."<br>";
    $email_message .= "Telephone:"."\t".clean_string($telephone)."<br>";
    $email_message .= "Comments:"."\t".clean_string($comments)."<br>"."<br>"."\n";

 $data = chunk_split(base64_encode($data)); 
$email_message .= "--{$mime_boundary}\n" . 
                  "Content-Type: {$fileatt_type};\n" . 
                  " name=\"{$fileatt_name}\"\n" . 
                  "Content-Disposition: attachment;\n" . 
                  " filename=\"{$fileatt_name}\"\n" . 
                  "Content-Transfer-Encoding: base64\n\n" .
                 $data . "\n\n" . 
                  "--{$mime_boundary}--\n";
     
// create email headers
$headers .= "\n" . 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);  

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.