How to Send Mail With Attachment in PHP

In my previous article, we have discussed about how to send mail with PHP mail function and also with use of Simple mail Transfer Protocol (SMTP) with attachment.

In this tutorial, we will learn how to send mail with attachment in PHP without SMTP.

By default PHP mail function does not support HTML or attachment .

How to Send Mail With Attachment in PHP

So we require to define header and Multipurpose Internet Mail Extensions (MIME) in our PHP snippet to send mail with attachment.

First create a HTML form with input type file and form enctype attribute as “multipart/form-data” which will send form-data encoded as “multipart/form-data” to server on form submit.

HTML

<form method="POST" enctype="multipart/form-data">
<label>Name</label><input type="text" name="name"><br>
<label>Email</label><input type="email" name="email"><br>
<label>File</label><input type="file" name="file"><br>
<input type="submit" name="submit" value="Send">
</form>

PHP

PHP snippet to send mail with attachment on form submission

<?php 
if(isset($_POST['submit'])):

//form data 
$from    =  $_POST['email'];
$subject =  "Mail with Attachment in PHP";
$msg     =  "Message body of Mail";
$to      =  "contact@example.com";

//get file details for attachment
$file_tmp_name =  $_FILES['file']['tmp_name'];
$file_name     =  $_FILES['file']['name'];
$file_size     =  $_FILES['file']['size'];
$file_type     =  $_FILES['file']['type'];
$file_error    =  $_FILES['file']['error'];
//boundary
$boundary = md5("phpcluster");

//check for file error
if($file_error==1)
{
echo $file_error;
die();
}

 //open and read uploaded file 
$op_file      = fopen( $file_tmp_name,"r");
$content      = fread($op_file, $file_size);
fclose($op_file);
$file_content = chunk_split(base64_encode($content));     


//headers for attachment file
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from."\r\n";
$headers .= "Content-Type: multipart/mixed;boundary = $boundary\r\n";
  
//for plain text message
$message .= "--$boundary\r\n";
$message .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n\r\n".chunk_split(base64_encode($msg)); 
  

//Add Attachment file
$message .= "--$boundary\r\n";
$message .= "Content-Type: $file_type; name=".$file_name."\r\n";
$message .= "Content-Disposition: attachment; filename=".$file_name."\r\n";
$message .= "Content-Transfer-Encoding: base64\r\n".$file_content; 



  $mail = @mail($to, $subject, $message, $headers);

  if($mail):
  echo "Mail Sent .. Success";
  else:
  echo "mail Send .. error!!";
  endif;
  
endif;
?>

Put HTML form on same page with below PHP snippet. Otherwise we can add action in HTML form to send its data to PHP file and send mail with attachment.

Here we have put static text in subject and message. You can also try to make dynamic with form input value. That’s it.

Leave a Comment