<form enctype=”multipart/form-data” method=”POST” action=””>
Name<input type=”text” name=”name” /><br/>
Email<input type=”email” name=”email” /><br/>
Phone<input type=”tel” name=”phone” /><br/>
Message<textarea name=”message”></textarea><br/>
Attachment<input type=”file” name=”my_files[]” multiple/><br/>
<input type=”submit” value=”Submit” />
</form>
<?php
if($_POST){
$subject = “Subject”;
$recepient = “recipient@email.com”;
$attachments = $_FILES[‘my_files’];
$file_count = count($attachments[‘name’]); //count total files attached
$boundary = md5(“sanwebe.com”);
//construct a message body to be sent to recipient
$message_body =”Name : “.$_POST[‘name’].”\r\n”;
$message_body.=”Phone : “.$_POST[‘phone’].”\r\n”;
$message_body.=”Email : “.$_POST[’email’].”\r\n”;
$message_body.=”Message : “.$_POST[‘message’].”\r\n”;
if($file_count > 0){ //if attachment exists
//header
$headers = “MIME-Version: 1.0\r\n”;
$headers .= “From:”.$_POST[’email’].”\r\n”;
$headers .= “Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n”;
//message text
$body = “–$boundary\r\n”;
$body .= “Content-Type: text/plain; charset=ISO-8859-1\r\n”;
$body .= “Content-Transfer-Encoding: base64\r\n\r\n”;
$body .= chunk_split(base64_encode($message_body));
//attachments
for ($x = 0; $x < $file_count; $x++){
if(!empty($attachments[‘name’][$x])){
if($attachments[‘error’][$x]>0) //exit script and output error if we encounter any
{
$mymsg = array(
1=>”The uploaded file exceeds the upload_max_filesize directive in php.ini”,
2=>”The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form”,
3=>”The uploaded file was only partially uploaded”,
4=>”No file was uploaded”,
6=>”Missing a temporary folder” );
print $mymsg[$attachments[‘error’][$x]];
exit;
}
//get file info
$file_name = $attachments[‘name’][$x];
$file_size = $attachments[‘size’][$x];
$file_type = $attachments[‘type’][$x];
//read file
$handle = fopen($attachments[‘tmp_name’][$x], “r”);
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= “–$boundary\r\n”;
$body .=”Content-Type: $file_type; name=”.$file_name.”\r\n”;
$body .=”Content-Disposition: attachment; filename=”.$file_name.”\r\n”;
$body .=”Content-Transfer-Encoding: base64\r\n”;
$body .=”X-Attachment-Id: “.rand(1000,99999).”\r\n\r\n”;
$body .= $encoded_content;
}
}
}else{ //send plain email otherwise
$headers = “From:”.$_POST[’email’].”\r\n”.
“X-Mailer: PHP/” . phpversion();
$body = $message_body;
}
$sentMail = mail($recepient, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo “<scr ipt>alert(‘Success.’);</script>”; //exit;
}else{
echo “<scr ipt>alert(‘Failure.’);</script>”; //exit;
}
}
?>
Reference : https://www.sanwebe.com/2011/01/send-php-mail-with-attachment
You must be logged in to post a comment.