Jump to content

Image Attatchment in Email being returned as Raw Code?!?


Darrenjs1210

Recommended Posts

Ok so I followed Buddski's advice to use MIME for the attatchment. (thanks for the help by the way, definitely headed in the right direction now.... i think...)

 

The image now successfully uploads to temp_folder on submit, the email is then delivered with correct text variables (name, phone, address etc.).

 

However, instead of their being an image included - there is just raw code.

 

If anyone could help with the final fix you may just save my sanity!

 

Thanks.

 


    <?php

    ini_set("sendmail_from", "darren@mywebsite.co.uk");
    ini_set("SMTP", "smtp.myhosts.co.uk");

    // Subject and Email Destinations //
    $emailSubject = 'Work Email!';
    $webMaster = 'darren@mywebsite.co.uk';

    // Gathering Data Variables //
    $name = trim($_POST['name']);

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

    // Add the headers for a file attachment //
    $headers .= "\nMIME-Version: 1.0\n" .
    "Content-Type: multipart/mixed;\n" .
    " boundary=\"{$mime_boundary}\"";

    // Add a multipart boundary above the plain message //
    $message ="This is a multi-part message in MIME format.\n\n";
    $message.="--{$mime_boundary}\n";
    $message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
    $message.="Content-Transfer-Encoding: 7bit\n\n";
    $message.= "Name: ".$name."\n";

    //The file type of the attachment //
    $file_type = 'text/csv';
    // The place the files will be uploaded to (currently a 'files' directory) //
    $upload_path = './uploads/';	
    // Get the name of the file (including file extension) //
    $filename = $_FILES['userfile']['name'];
    // Get the extension from the filename //
    $ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
    // Configuration of File Uploaded //
    $allowed_filetypes = array('.jpg','.JPEG','.jpeg','.gif','.bmp','.png');
    $max_filesize = 2000000; 
    (move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename));

    //This attatches the image file to the email //
    $message .= chunk_split(base64_encode(file_get_contents($upload_path . $filename)));

    // Send the Email with the attatchment.	
    $success = mail($webMaster, $emailSubject, $message, $headers, "-fdarren@dsinteriorsltd.co.uk");
    ?>

>>>is returning this to my email...

    MIME-Version: 1.0
    Content-Type: multipart/mixed;
    boundary="==Multipart_Boundary_x9cbb390d8be528476c5423025ed1e4ccx"

    This is a multi-part message in MIME format.

    --==Multipart_Boundary_x9cbb390d8be528476c5423025ed1e4ccx
    Content-Type: text/plain; charset="iso-8859-1"
    Content-Transfer-Encoding: 7bit

    Name: darren

    /9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB
    AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB
    AQEBAQEB...........................................................
    ..........this code goes on like this for ages.

Link to comment
Share on other sites

It is doing that because you are adding the raw data under the text/plain mime boundary

As per my original script, you need to start separate each part of the email.

 

Headers: These tell the email client how to handle the information contained in the email.

$headers = 'From: ' . $email . "\r\n" .
'To: '.$webMaster."\r\n" .
'Reply-To: ' . $email . "\r\n" .
'MIME-Version: 1.0' . "\r\n" .
'Content-Type: multipart/mixed;' . "\r\n" . " boundary=\"".$mime_boundary."\"";

Attachment: This creates the first part of the email "body" and tells us that it is an attachment and is of *insert type*

$message = "--".$mime_boundary."\n" .
"Content-Type: {$file_type};\n" .
" name=\"{$filename}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$filename}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
chunk_split(base64_encode(file_get_contents($upload_path . $filename))) . "\n\n";

HTML\Text Part: This creates the section that will be displayed to the user in the email client

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

Link to comment
Share on other sites

That works perfectly.

 

The descriptions you have used at the top of each of the 3 sections gives me a much better understanding of how the script works.

 

I'll keep learning, hopfully one day I'll actually 'get' PHP and be able to write my own code without any errors.

 

Thanks for your help on this one Buddski, really appreciate it!!

Link to comment
Share on other sites

No worries, got there in the end :)

 

Just have a slight issue with the fact that the email won't send unless a file is attatched.

 

Spent all day yesterday trying to troubleshoot it but no luck.

 

I thought maybe swapping the 'Attatchment' and 'HTML Part' around might be the answer....

 

.....doing that actually sends the email with an empty attatchment and no variables (name, address etc.)

Link to comment
Share on other sites

Thanks mate, this is the new code - as edited by yourself (looks pretty smart!).

 

Am I right in thinking I need to use 'If' statements to get this to still send even if a file is not attatched....

 

Just a guess.... am probably way off!  :confused:

 

 

       <?php

ini_set("sendmail_from", "darren@myemail.co.uk");
ini_set("SMTP", "smtp.fasthosts.co.uk");

// Subject and Email Destinations.
$emailSubject = 'Work Email!';
$webMaster = 'darren@mywebsite.co.uk';

	// Gathering Data Variables.
	$name = trim($_POST['name']);
	$address = trim($_POST['address']);
	$postcode = trim($_POST['postcode']);
	$phone = trim($_POST['phone']);
	$email = trim($_POST['email']);
	$details = trim($_POST['details']);
	$contactby = trim($_POST['contactby']);

		//The file type of the attachment.
		$file_type = 'text/csv';
		// The place the files will be uploaded to (currently a 'files' directory).
		$upload_path = './uploads/';	
		// Get the name of the file (including file extension).
		$filename = $_FILES['userfile']['name'];
		// Get the extension from the filename.
		$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
		// Configuration of File Uploaded
		$allowed_filetypes = array('.jpg','.JPEG','.jpeg','.gif','.bmp','.png');
		$max_filesize = 2000000; 
		(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename));

// create a boundary string. It must be unique.
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

// Headers: These tell the email client how to handle the information contained in the email.
$headers = 'MIME-Version: 1.0' . "\r\n" .
	        'Content-Type: multipart/mixed;' . "\r\n" . " boundary=\"".$mime_boundary."\"";

// Attachment: This creates the first part of the email "body" and tells us that it is an attachment and is of *insert type*
$message = "--".$mime_boundary."\n" .
			"Content-Type: {$file_type};\n" .
			"Content-Disposition: attachment;\n" .
			" filename=\"{$filename}\"\n" .
			"Content-Transfer-Encoding: base64\n\n" .
			//This attatches the image file to the email.
			chunk_split(base64_encode(file_get_contents($upload_path . $filename))) . "\n\n";

// HTML\Text Part: This creates the section that will be displayed to the user in the email client
$message .="This is a multi-part message in MIME format.\n\n";
$message.="--{$mime_boundary}\n";
$message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message.="Content-Transfer-Encoding: 7bit\n\n";
$message.= "My Name is: ".$name."\n";
$message.= "I live at: ".$address."\n";
$message.= "The Postcode is: ".$postcode."\n";
$message.= "My digits: ".$phone."\n";
$message.= "My email addy: ".$email."\n";
$message.= "Work I need done: ".$details."\n";
$message.= "You're probably best contacting me by: ".$contactby."\n";

// Send the Email with the attatchment.	
$success = mail($webMaster, $emailSubject, $message, $headers, "-fdarren@myemail.co.uk");
   
        ?>

Link to comment
Share on other sites

ok, this is strange. I went and did a chmod 777 to this file.

 

now the email sends even when you don't attatch a file  :P

 

I just get either an empty attatchment, or a weird bit of code at the top of the email (when viewing receiving it on my iPhone)

 

Its about 30 characters long, symbols in it include a 'Yen', a 'TM' normal letters, and some Russian looking ones.

 

Is there a way of stopping that showing... if there is no file attatched. Soz... i'm probably doing your head in by now!! Getting a bit obsessed with this contact form. lol.

 

 

 

Link to comment
Share on other sites

Ive got beer to keep my head from going in so dont stress :)

There are a few things that need to be removed from the code when there is no attachment..

Ill write up the code for you and chuck in a few notes to keep you going you can write the code to detect if it has an attachment :)

       <?php

ini_set("sendmail_from", "darren@myemail.co.uk");
ini_set("SMTP", "smtp.fasthosts.co.uk");

// Subject and Email Destinations.
$emailSubject = 'Work Email!';
$webMaster = 'darren@mywebsite.co.uk';

	// Gathering Data Variables.
	$name = trim($_POST['name']);
	$address = trim($_POST['address']);
	$postcode = trim($_POST['postcode']);
	$phone = trim($_POST['phone']);
	$email = trim($_POST['email']);
	$details = trim($_POST['details']);
	$contactby = trim($_POST['contactby']);

		//The file type of the attachment.
		$file_type = 'text/csv';
		// The place the files will be uploaded to (currently a 'files' directory).
		$upload_path = './uploads/';	
		// Get the name of the file (including file extension).
		$filename = $_FILES['userfile']['name'];
		// Get the extension from the filename.
		$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
		// Configuration of File Uploaded
		$allowed_filetypes = array('.jpg','.JPEG','.jpeg','.gif','.bmp','.png');
		$max_filesize = 2000000; 
		(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $filename));

// This variable should be boolean, true if there is an attachment and false if there isnt
$has_attachment = something_to_check_to_see_if_an_attachment_is_set;

// Create an empty variable for the message to be appended to
$message = '';

// Specify the default headers //
$headers = 'MIME-Version: 1.0' . "\r\n" .
	        "Content-Type: text/plain; charset=\"iso-8859-1\"\n";
	        
if ($has_attachment) {
	// The boundary is only needed in the attachment style email
	// so... create a boundary string. It must be unique.
	$semi_rand = md5(time());
	$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

	// Ok we have an attachment so we need to overwrite the default headers //
	$headers = 'MIME-Version: 1.0' . "\r\n" .
	'Content-Type: multipart/mixed;' . "\r\n" . " boundary=\"".$mime_boundary."\"";
	        
	// Now we throw in the section the contains the actual attachment.
	$message .= "--".$mime_boundary."\n" .
	"Content-Type: {$file_type};\n" .
	"Content-Disposition: attachment;\n" .
	" filename=\"{$filename}\"\n" .
	"Content-Transfer-Encoding: base64\n\n" .
	chunk_split(base64_encode(file_get_contents($upload_path . $filename))) . "\n\n";

	// Once the attachment is done, we add the next half which is the boundary for the rest of the email content
	$message .="This is a multi-part message in MIME format.\n\n";
	$message.="--{$mime_boundary}\n";
	$message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
	$message.="Content-Transfer-Encoding: 7bit\n\n";
}
// This ends our checking script // if the has_attachment condition wasnt true it will just attach the below to the empty $message variable
// If it was successful, it will add it to all the stuff we have already added to the message

$message.= "My Name is: ".$name."\n";
$message.= "I live at: ".$address."\n";
$message.= "The Postcode is: ".$postcode."\n";
$message.= "My digits: ".$phone."\n";
$message.= "My email addy: ".$email."\n";
$message.= "Work I need done: ".$details."\n";
$message.= "You're probably best contacting me by: ".$contactby."\n";

// Send the Email with the attatchment.	
$success = mail($webMaster, $emailSubject, $message, $headers, "-fdarren@myemail.co.uk");
   
        ?>

If you have any question dont hesitate to ask.

Ive made it pretty obvious which part youll need to edit :)

Link to comment
Share on other sites

Nice one Buddski, like the way you made me learn Boolean whilst using your code - that was quite cool.

 

So I used $filename for that. Obviously if it there is a filename that means the $has_attatchment will be true.

 

I also added my own 'if' statements to filter out any uploads/spam that I don't want.....

 

// Check if the filetype is allowed, if not DIE and inform the user.

$allowed_filetypes = array('.jpg','.JPEG','.jpeg','.gif','.bmp','.png');

if(!in_array($ext,$allowed_filetypes))

      die('The file you attempted to upload is not allowed.');

 

.......and included this statement just before we //threw in the contents of the attatchment// which is all wrapped up in {has_attatchment brackets} ......phew!!!!!

 

Now everything works exactly as it is supposed to, and I've learnt quite a lot. Namely that you can do some pretty neat stuff with PHP.

 

Thanks again for all your help with that. Great job!!

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.