hi all

i'm trying to send an email with an attachment from a form and i've found a few scripts on the internet but can't make them work. has anyone got any simple code that works for sure? and another question: is the attachment sent directly or it has to be uploaded on the server first so i guess i have to modify the folders permissions on the server?

thanks for any help :)

Recommended Answers

All 4 Replies

hi all

i'm trying to send an email with an attachment from a form and i've found a few scripts on the internet but can't make them work. has anyone got any simple code that works for sure? and another question: is the attachment sent directly or it has to be uploaded on the server first so i guess i have to modify the folders permissions on the server?

thanks for any help :)

Have you tried the pear Mail library?
http://pear.php.net/package/Mail

Another good mail is SwiftMailer. The docs on attachments:
http://swiftmailer.org/docs/message-attachments

Create a file called mailtest.php and stick the code below into it - should do the trick. If you are testing it locally then you will need a mail server running on your machine.

It is pretty basic, you'll have to add some stuff for handling any other input fields. It will give you the basic attachment routine.

Remember to change the email at the top, the $uploaddir variable and alter $allowedExtensions to suit.

<?php
$to = "your@email.co.uk"; // Change to your email
$from = "some@email.co.uk"; // Perhaps you will collect this as part of the form
$subject = 'Test Email'; // Again, perhaps you will collect this as part of the form
$message = 'Test message';  // And once again perhaps you will collect this as part of the form
$uploaddir = 'uploads\\'; // You will need to create a directory and put its name here. The directory will need permissions set so that the script can move files into it and then delete them. Don't remove the \\
$error_state = false;
$random_hash = md5(date('r', time())); 
$page_output = '<form action="" method="post" enctype="multipart/form-data">
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="5000000" />
<input type="file" name="attachedfile" /><br />
<input type="submit" name="submit" value="Send" /></form>
';
$allowedExtensions = array("rtf", "doc", "docx", "pdf", "odt"); // change this to suit your needs
function isAllowedExtension($fileName) {
	global $allowedExtensions;
	return in_array(end(explode(".", $fileName)), $allowedExtensions);
}

if (isset($_REQUEST["submit"]) && $_REQUEST["submit"] == 'Send') {
	if ($_FILES['attachedfile']['error'] == 0) {
		$file = $_FILES['attachedfile'];
		if(isAllowedExtension($file['name'])) {
			$uploadfile = $uploaddir . basename($_FILES['attachedfile']['name']);
			move_uploaded_file($_FILES['attachedfile']['tmp_name'], $uploadfile);
			$attachment = chunk_split(base64_encode(file_get_contents($uploadfile))); 
		} else {
			$page_output = 'That filetype is not allowed. <a href="mailtest.php">Back</a>';
			$error_state = true;
		}
		$headers = "From: " . $from . "\r\nReply-To: " . $from; 
		$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\""; 
		ob_start();
?> 
--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>" 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="utf-8" 
Content-Transfer-Encoding: 7bit

<?php echo $message ?>


--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="utf-8" 
Content-Transfer-Encoding: 7bit

<div style="font-family:Arial, Helvetica, sans-serif; font-size:12px; margin:5px;">
<?php echo str_replace("\r\n", '<br />' . "\r\n", $message) . "\r\n" ?>
</div>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>  
Content-Type: <?php echo $_FILES['attachedfile']['type']; ?>; name="<?php echo $_FILES['attachedfile']['name']; ?>"  
Content-Transfer-Encoding: base64  
Content-Disposition: attachment; filename="<?php echo $_FILES['attachedfile']['name']; ?>"  

<?php echo $attachment; ?> 


--PHP-mixed-<?php echo $random_hash; ?>-- 
<?php 
		$message = ob_get_clean();
		if (!$error_state) {
			mail( $to, $subject, $message, $headers ); 
			unlink($uploadfile);
			$page_output = 'Your message has been sent. <a href="mailtest.php">Back</a>';
		}
	}
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Mail Test</title>
<style type="text/css">
<!--
#wrap {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 10px;
	width: 400px;
	margin-left:auto;
	margin-right:auto;
}
-->
</style>
</head>

<body>
<div id="wrap">
<?php echo $page_output ?>
</div>
</body>
</html>

Hope this helps,

Simon.

thanks a lot for the replies guys. i tried different things yesterday and got something almost working. the thing is, the attachment is sent correctly when i send it from my localhost (i use xampp) but is blank when i send it from the internet (online web server). i can't figure out why. do you have any ideas? here's my code:

 <?php 
        if (!isset($_POST['Submit'])) {
            echo "<h4>Αποστολή εξόδων</h4>";


            }else{

        $from = "something@something.com";
        $to = "something@something.com";
        $subject = "=?UTF-8?B?".base64_encode('ΕΞΟΔΑ ΚΟΙΝΟΧΡΗΣΤΩΝ')."?=";

        // generate a random string to be used as the boundary marker
        $mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";

        // store the file information to variables for easier access
       $tmp_name = $_FILES['filename']['tmp_name'];
       $type = $_FILES['filename']['type'];
       $name = $_FILES['filename']['name'];
       $size = $_FILES['filename']['size'];

        $message = "Επώνυμο: " . $eponimo .$tmp_name . 
         "\n\n".$sxolia ;


        // check to make sure that it is an uploaded file and not a system file
        if(is_uploaded_file($tmp_name)){

            // open the file for a binary read
             $file = fopen($tmp_name,'rb');

            // read the file content into a variable
             $data = fread($file,filesize($tmp_name));

            // close the file
             fclose($file);


             // now we encode it and split it into acceptable length lines
             $data = chunk_split(base64_encode($data));

        }

        // now we'll build the message headers
        $headers = "From: $from\r\n" .
         "MIME-Version: 1.0\r\n" .
         "Content-Type: multipart/mixed;\r\n" .
         " boundary=\"{$mime_boundary}\"";


        // next, we'll build the message body
        // note that we insert two dashes in front of the
        // MIME boundary when we use it
        $message .= "This is a multi-part message in MIME format.\n\n" .
         "--{$mime_boundary}\n" .
         "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
         "Content-Transfer-Encoding: 7bit\n\n" .
         $message . "\n\n";


        // now we'll insert a boundary to indicate we're starting the attachment
        // we have to specify the content type, file name, and disposition as
        // an attachment, then add the file content and set another boundary to
        // indicate that the end of the file has been reached
          $message .= "--{$mime_boundary}\n" .
         "Content-Type: {$type};\n" .
         " name=\"{$name}\"\n" .
         //"Content-Disposition: attachment;\n" .
         //" filename=\"{$fileatt_name}\"\n" .
         "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n" .
         "--{$mime_boundary}--\n";


         // now we just send the message
      if (@mail($to, $subject, $message, $headers))
         echo "Message Sent";
      else
         echo "Failed to send";







        }



   ?>

Look at the email source - does it have the appropriate boundaries? If so, is there any text at all where the attachment should be?

Also, I have had an issue on some servers where the attachment won't attach unless it is first moved out of the temp folder to another location. Not sure why, maybe the file gets deleted before the attchment process is complete, maybe it has something to do with permissions, whatever, moving the file first can help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.