
For the web application, we mostly and frequently use web form. There are various type of web form used to get the user’s input like Contact, Registration, feedback. Contact or feedback form is used for online communication and submitted form data is sent via email instantly. You can easily send mail with attachment and form data using mail() function. In this blog, we are going to understand how to send email with attachment on form submission using PHP.
We are going to create a contact form with file attachment option which will send an email to a specific email address on form submission. We will divide our code into two parts for better understanding. We are going to put HTML code in first part and in second part we will put the PHP code.
HTML form with File Upload Field
Firstly, we are going to create a basic contact form with some basic fields which are name, email, subject, message and a choose file field.
<form method=”post” action=”” enctype=”multipart/form-data”>
<div class=”form-group”>
<input type=”text” name=”name” class=”form-control” value=”<?php echo !empty($postData[‘name’])?$postData[‘name’]:”; ?>” placeholder=”Name” required=””>
</div>
<div class=”form-group”>
<input type=”email” name=”email” class=”form-control” value=”<?php echo !empty($postData[’email’])?$postData[’email’]:”; ?>” placeholder=”Email address” required=””>
</div>
<div class=”form-group”>
<input type=”text” name=”subject” class=”form-control” value=”<?php echo !empty($postData[‘subject’])?$postData[‘subject’]:”; ?>” placeholder=”Subject” required=””>
</div>
<div class=”form-group”>
<textarea name=”message” class=”form-control” placeholder=”Write your message here” required=””><?php echo !empty($postData[‘message’])?$postData[‘message’]:”; ?></textarea>
</div>
<div class=”form-group”>
<input type=”file” name=”attachment” class=”form-control”>
</div>
<div class=”submit”>
<input type=”submit” name=”submit” class=”btn” value=”SUBMIT”>
</div>
</form>
Send Email with attachment on Form Submission
- Get the submitted form data using $_POST in PHP.
- Validate form data to check whether the mandatory fields are not empty.
- Validate email address using FILTER_VALIDATE_EMAIL in PHP.
- Check the file extension to allow certain file formats (PDF, Image, and MS Word file).
- Upload file to the server.
- Add form data and uploaded file to the email content.
- Send an email with attachment to the specified recipient using PHP mail() function.
The following code handles the form submission and email sending with attachment functionality using PHP
$postData = $uploadedFile = $statusMsg = '';
$msgClass = 'errordiv';
if(isset($_POST['submit'])){
// Get the submitted form data
$postData = $_POST;
$email = $_POST['email'];
$name = $_POST['name'];
$subject = $_POST['subject'];
$message = $_POST['message'];
// Check whether submitted data is not empty
if(!empty($email) && !empty($name) && !empty($subject) && !empty($message)){
// Validate email
if(filter_var($email, FILTER_VALIDATE_EMAIL) === false){
$statusMsg = 'Please enter your valid email.';
}else{
$uploadStatus = 1;
// Upload attachment file
if(!empty($_FILES["attachment"]["name"])){
// File path config
$targetDir = "uploads/";
$fileName = basename($_FILES["attachment"]["name"]);
$targetFilePath = $targetDir . $fileName;
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// Allow certain file formats
$allowTypes = array('pdf', 'doc', 'docx', 'jpg', 'png', 'jpeg');
if(in_array($fileType, $allowTypes)){
// Upload file to the server
if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
$uploadedFile = $targetFilePath;
}else{
$uploadStatus = 0;
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$uploadStatus = 0;
$statusMsg = 'Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.';
}
}
if($uploadStatus == 1){
// Recipient
$toEmail = '[email protected]';
// Sender
$from = '[email protected]';
$fromName = 'RexcelIT';
// Subject
$emailSubject = 'Contact Request Submitted by '.$name;
// Message
$htmlContent = '
//Contact Request Submitted
Name: '.$name.'
Email: '.$email.'
Subject: '.$subject.'
Message:
'.$message.'
';
// Header for sender info
$headers = "From: $fromName"." <".$from.">";
if(!empty($uploadedFile) && file_exists($uploadedFile)){
// 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 = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
if(is_file($uploadedFile)){
$message .= "--{$mime_boundary}\n";
$fp = @fopen($uploadedFile,"rb");
$data = @fread($fp,filesize($uploadedFile));
@fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($uploadedFile)."\"\n" .
"Content-Description: ".basename($uploadedFile)."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($uploadedFile)."\"; size=".filesize($uploadedFile).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $email;
// Send email
$mail = mail($toEmail, $emailSubject, $message, $headers, $returnpath);
// Delete attachment file from the server
@unlink($uploadedFile);
}else{
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($toEmail, $emailSubject, $htmlContent, $headers);
}
// If mail sent
if($mail){
$statusMsg = 'Your contact request has been submitted successfully !';
$msgClass = 'succdiv';
$postData = '';
}else{
$statusMsg = 'Your contact request submission failed, please try again.';
}
}
}
}else{
$statusMsg = 'Please fill all the fields.';
}
}
?>
Now, you can send form data through email with a file attachment. You can specify any type of file to upload and send with the email on form submission.