In this Blog, you will learn how to attach file in email with simple PHP mail() function.
<form action='send_email.php' method='POST'>
<div class='form-group'>
<label>Send To</label>
<span class='abstric'>*</span>
<input type='text' name='email' id='emailto' class='form-control' placeholder='Enter Email ID'>
<span class='error_msg'></span>
</div>
<div class='form-group'>
<span style='color: red' class='eremail'></span>
</div>
<div class='form-group'>
<label>Subject</label>
<span class='abstric'>*</span>
<input type='text' name='subject' id='subject' class='form-control' placeholder='Enter Email Subject'>
<span class='error_msg'></span>
</div>
<div class='form-group'>
<span style='color: red' class='esubject'></span>
</div>
<div class='form-group'>
<label>Message</label>
<span class='abstric'>*</span>
<input name='message' id='message' class='form-control' placeholder='Enter Email Message' rows='3'>
<span class='error_msg'></span>
</div>
<div class='form-group'>
<span style='color: red' class='emsg'></span>
</div>
<div id='attach_csv_div' style='display:none'>
<div class='form-group'>
<input type='file' name='attachment' id='attachment' class='form-control' >
<span style='color: red' class='eattachment'></span>
</div>
<div class='form-group'>
<input type='submit' name='submit' value='Submit' class='btn btn-primary'>
</div>
</form>
Now our html form is ready.
The PHP mail() function with some MIME type headers can be used to send email with attachment in PHP. In the following example code, MIME and Content-Type headers are used with mail() function to send email with attachment using PHP.
The following script lets you send both types of messages (text or HTML) with an attachment file to the email.
File: send_email.php
$message = $_POST['message'];
$to = $_POST['email'];
$subject = $_POST['subject'];
$body = '
<h3>PHP Email with Attachment by Kingsoftware</h3>
<p>This email is sent from the PHP script with attachment.</p>
<p>Message : '.$message.'</p>
<p>This email is sent from the PHP script with attachment.</p>
';
$semi_rand = md5(uniqid(time()));
$headers = "From: abcd@example.com \r\n";
$headers .= "Cc: abcd@example.com \r\n";
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "MIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$strFilesName = $_FILES["attachment"]["name"];
$strContent = chunk_split(base64_encode(
file_get_contents($_FILES["attachment"]["tmp_name"])));
$email_message = "--{$mime_boundary}\n" .
"Content-Type:text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$body . "\n\n";
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: application/octet-stream;\n" .
" name=\"{$strFilesName}\"\n" .
" //"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$strContent .= "\n\n" .
"--{$mime_boundary}--\n";
$result = mail($to,$subject,$email_message,$headers);