How to send an attachment with email in PHP?

Sending an email is a very common activity in any web application. PHP has mail() function to send email form code. Sometimes we need to send attachment file with email. Attachment can be any image, word document, PDF etc.

Let’s have any form example where we will fill user details, upload a word document and will email that document to email by PHP code. While creating a form to upload a file, always keep in mind to use enctype=”multipart/form-data” tag in a form element. It will tell the browser that this form will be used to upload a file.

<form method="POST" name="send_attachment"
action="send_email.php" enctype="multipart/form-data"> 

<label for='name'>Name: </label>
<input type="text" name="name" >

<label for='email'>Email: </label>
<input type="text" name="email" >

<label for='uploaded_file'>Select A File To Upload:</label>
<input type="file" name="uploaded_file">

<input type="submit" value="Submit" name='submit'>
</form>

In PHP Script, first we will validate form submit and attachment validation.

if(isset($_POST['Submit']) && isset($_FILES['uploaded_file'])) 
)

We can access the uploaded file by the $_FILE array. This $_File array contains all attributes of the file like name, size, type etc.

$message = " Name : $_POST['name'] <br>
             Email : $POST['email'] ";

//Get the file name -
$name = $_FILES['uploaded_file']['name'];

// upload file path
$path = "/uploads";

// copy the file to specific upload folder
$file = $path.$filename;
$file_size = filesize($file);

//read the uloaded file and base64 encode
 $handle = fopen($file, "r");
 $content = fread($handle, $file_size);
 fclose($handle);
 $content = chunk_split(base64_encode($content));

 $boundary= md5(uniqid(time()));  // define boundary

// Email header
 $header = "From: ".$from_name." <".$from_mail.">\r\n";
 $header .= "Reply-To: ".$replyto."\r\n";
 $header .= "MIME-Version: 1.0\r\n";
 $header .= "Content-Type: multipart/mixed; 
 $headers .= "boundary = $boundary\r\n"; //Defining the Boundary 

// plain text
  $body = "--$boundary\r\n"; 
 $body.= "Content-type:text/plain; charset=iso-8859-1\r\n";
 $body.= "Content-Transfer-Encoding: 7bit\r\n\r\n";
 $body.= $message."\r\n\r\n";

// Attachment 
 $body = "--$boundary\r\n"; 
 $body.= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
 $body.= "Content-Transfer-Encoding: base64\r\n";
 $body.= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
 $body.= $content."\r\n\r\n";


 if (mail($mailto, $subject, "$body", $header)) {
 echo "mail send";
 } else {
 echo "mail not send";
 }

For any issue, please write in comment.

Leave a Reply