Unable to send mail attachment

Discussion on PHP Scripting
no avatar
ellipse4
 
Posts: 1
Joined: Sun Jun 02, 2013 10:39 am

Unable to send mail attachment

by ellipse4 » Sun Jun 02, 2013 10:46 am

I have been trying for hours to e-mail an attachment but just cannot get it right. I have used examples and variations of scripts from many websites, including this one, to no avail. Below is the code I have as it stands at present:

<?php

unset($_POST['submit']);
//unset($_FILES['photo']['name']);
//unset($_FILES['photo']['temp_name']);
//unset($_FILES['photo']['extension']);
//unset($_FILES['photo']['type']);

echo "<form method=".'"'."post".'"'." enctype=".'"'."multipart/form-data".'"'.">";
echo "Photo <input type=".'"'."file".'"'." name=".'"'."photo".'"'." size=50></input>";
echo "<input type=".'"'."submit".'"'." name=".'"'."submit".'"'."/>";
echo "</form>";

if (isset($_POST['submit']))
{
$name = $_FILES['photo']['name'];
$temp_name = $_FILES['photo']['tmp_name'];
$extension = substr(strtolower($name),strpos($name,".")+1);
$type = $_FILES['photo']['type'];

if ($extension=='jpg'||$extension=='jpeg')
{
$to = "johndoe@johndoe.com";
$subject = "A Picture for You";
$message = "Here is your picture.";

//get details of the file that needs to be sent as an attachment

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

//generate the boundary string
$semi_rand = md5(time());
$boundary = "==Multipart_Boundary_x{$semi_rand}x";

//Base64 encode the file data
$data = chunk_split(base64_encode($data));


//Generate the main header

$header = "From:xyz@somedomain.com\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$boundary\r\n";
$header .= "--$boundary\r\n";


//Generate the text header

$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$boundary\r\n";

//Generate the attachment header
$header .= "Content-Type:image/jpeg; ";
$header .= "name=\$name\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\$name\r\n\n";
$header .= "$data\r\n";
$header .= "--$boundary--";

mail($to, $subject, $message, $header);

};
};



?>


I introduced Unset as the form kept picking up previously selected images. I also do not understand why some of the lines in the headers end with \r\n, some with \r\r\n and some with neither of these.

I would really appreciate it if someone could tell me where I went wrong and shed light on when to use \r\n or \r\r\n.

Return to PHP Script

cron