Send File Attachment by using PHP Form

By using this script you can simply sent the attachments in php
HTML: index.php

<form name="form1" enctype="multipart/form-data" method="post" action="mail.php">
<label>Your Name
<input type="text" name="name" />
<label>Your Email
<input type="email" name="email" />
<input type="file" name="my_file" />
<input type="submit" name="button" value="Submit" />

PHP: mail.php

if($_POST && isset($_FILES['my_file']))
$from_email = 'Your Mail'; //sender email
$recipient_email = $_POST['mail'];
$user_email = $_POST['email'];
$subject = 'Mail From Mskv';
$message = $_POST['msg'];
//get file details we need
$file_tmp_name = $_FILES['my_file']['tmp_name'];
$file_name = $_FILES['my_file']['name'];
$file_size = $_FILES['my_file']['size'];
$file_type = $_FILES['my_file']['type'];
$file_error = $_FILES['my_file']['error'];
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
die('upload error');
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
$headers = "MIME-Version: 1.0rn";
$headers .= "From:".$from_email."rn";
$headers .= "Reply-To: ".$user_email."rn";
$headers .= "Content-Type: multipart/mixed; boundary = $boundaryrnrn";
//plain text
$body = "--$boundaryrn";
$body .= "Content-Type: text/plain; charset=ISO-8859-1rn";
$body .= "Content-Transfer-Encoding: base64rnrn";
$body .= chunk_split(base64_encode($message));
$body .= "--$boundaryrn";
$body .="Content-Type: $file_type; name="$file_name"rn";
$body .="Content-Disposition: attachment; filename="$file_name"rn";
$body .="Content-Transfer-Encoding: base64rn";
$body .="X-Attachment-Id: ".rand(1000,99999)."rnrn";
$body .= $encoded_content;
$sentMail = @mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
die('Your File Attachment successfully Mailed');
die('Could not send mail! Please check your PHP mail configuration.');

3 thoughts on “Send File Attachment by using PHP Form”

  1. Thanks for this code. It generates an error when you do not select a file.
    How to send the mail even when we didn’t select a file?
    Thank you

  2. php shows error “Parse error: syntax error, unexpected ‘$file_name’ (T_VARIABLE) in /storage/ssd2/010/2284010/public_html/sendEmail1.php on line 45”
    Please helpto resolve.

Leave a Reply

Your email address will not be published. Required fields are marked *