The following php script can be used to send web form mails with attachment
Use the following PHP code to send attachments through web form Email. You can send multiple attachments by using this code. To send multiple attachments no chnages needed in PHP code, but you need to make the changes in HTML form to input more than one attachments.
Changes Required in the below Script:
Replace your_id@yourdomain.com with the Email ID to which you would like to receive the mails.
Replace admin@yourdomain.com with the Email ID from which you would like to send the form mails.
You can download the full code with HTML form, Javascript form validation and PHP Scripts in the attachment below.
<?php
if(isset($_POST['Submit'])) {
$email_to = "your_id@yourdomain.com"; // Change This
$email_subject = "PHP Form Mail- With Attachment";
$thankyou = "thanks.html";
$email_sender = "admin@yourdomain.com"; // Change This
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
function died($error) {
echo "Sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.";
echo $error."";
echo "Please go back and fix these errors.";
die();
}
// multipart boundary
$email_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" . $email_message . "\n\n";
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// 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));
}
$email_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";
}
}
$headers = 'From: '.$email_sender."\r\n". // Mail will be sent from your Admin ID
'Reply-To: '.$Email."\r\n" . // Reply to Sender Email
'X-Mailer: PHP/' . phpversion();
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
@mail($email_to, $email_subject, $email_message, $headers);
header("Location: $thankyou");
?>