PHP mail with attachment

Introduction

Mail function is a php global function. mail() use to send emails quickly and easily.

PHP mail with attachment

<form enctype="multipart/form-data" method="POST" action="compose-mail-attach.php"> 
	<label>Your Name </label> <input type="text" name="sender_name" class="form-control" required />
	<label>Your Email </label> <input type="email" name="sender_email"  class="form-control" required  />
    <label>To Email </label><input type="email" name="recever_email" class="form-control"  required />
	<label>Subject </label><input type="text" name="subject" class="form-control" required  />
	<label>Message </label><textarea name="message" class="form-control"  required></textarea>
	<label>Attachment <input type="file" name="attachment" class="form-control"  required /></label> <br><br>
	<input type="submit" name="button" value="Submit" class="btn btn-primary" />
</form> 
<?php
if(isset($_POST['button']))
{
    $to = $_POST['recever_email'];
    $subject = $_POST['subject'];
    $message = $_POST['message'];
    $sender_name = $_POST['sender_name'];
    $sender_email = $_POST['sender_email'];
    $headers = "From: $sender_name<$sender_email>";
    // boundary
    $semi_rand = md5(time());
    $mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
    // headers for attachment
    $headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
    // multipart boundary
    $message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=ISO-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
    $message .= "--{$mime_boundary}\n";
    $filepath = 'uploads/'.$_FILES['attachment']['name'];
    move_uploaded_file($_FILES['attachment']['tmp_name'], $filepath); //upload the file
    $filename = $_FILES['attachment']['name'];
    $file = fopen($filepath, "rb");
    $data = fread($file, filesize($filepath));
    fclose($file);
    $data = chunk_split(base64_encode($data));
    $message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$filename\"\n" .
    "Content-Disposition: attachment;\n" . " filename=\"$filename\"\n" .
    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
    $message .= "--{$mime_boundary}\n";
    if(mail($to, $subject, $message, $headers))
    {
        ?>
        <p class="alert alert-success"><b>Email</b> Sended Successfully</p>
        <?php
    }
    else
    {
        echo "not working";
    }
}
?>