PHP code to send email with an attachment

Assume that we are getting message and file attachment from a html form. So the php code for processing that form and sending email with file attachment will be following.


//Getting Data submitted through form.
$otherData= $_POST['message']; //The text message
$afile = $_FILES['myFile'];

//Getting info about above taken file
$fileatttype = $afile['type'];
$fileattname = $afile['name'];

// Setting basic headers info
$headers = "From: info@website.com";

//Opeing the submitted file to read all data in it
$file = fopen($afile['tmp_name'],'rb');
$data = fread($file,$afile['size']);
fclose( $file );

//Making a random number to use afterwards with help of current time
$semi_rand = md5( time() );

//Defining the type of email as Mime email
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//Appending to headers, telling that its multipart message with text and attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";

//The text part of message in variable $otherData with other details
$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" .
$otherData . "\n\n";


//Encoding all the data read from file to "base64" the standard for email attachments

$data = chunk_split(base64_encode($data));

//Appending the file data to the email including the file name etc
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatttype};\n" .
" name=\"{$fileattname}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileattname}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";

//other details like the email subject and recipient's email address
$subject="New submission";
$to="email@anysite.com";

//Instruction to send email
mail($to, $subject, $message, $headers);
?>
Enjoy!, comment, suggetions, improvements and other coding tricks are most welcome.

Posted in |