The web form is a widely used element for web applications. Various types of forms are used on the website to submit user data. Contact, registration, and feedback forms are some of the most used web forms to get the user’s input. Generally, the text, textarea, and select input fields are used in the web form. But in some cases, the web form needs to allow the user to select a file. In this situation, you need to upload the selected file and attach it to the form data.
Contact or feedback form is used for online communication, and the submitted form data is sent via email instantly. When the contact form has a file upload field, the file needs to be sent via email as an attachment. Using the mail() function, you can easily send an email with attachments and form data in PHP. In this tutorial, we will show you how to send email with attachment on form submission using PHP.
This example code snippet provides an instant ability to create a contact form with a file attachment option and integrate it into the website. Also, an email will be sent to a specific email address with a file attachment. For a better understanding, we will divide the PHP contact form with email and file attachment script into two parts: HTML (Web Form) and PHP (Form Submission). You can place both parts of the code together on the web page where you want to integrate the contact us form with a file attachment.
Create an HTML form with some input elements (common contact fields: Name, Email, Subject, and Message) and a file input field.
enctype="multipart/form-data" in the form tag to allow file uploads.type="file" allows users to select a file from their device. The accept attribute specifies the allowed file types (PDF, Image, and MS Word files in this case).Display the form submission status (success or error messages) above the form.
$_POST superglobal array.htmlspecialchars() to prevent XSS attacks by escaping special characters in user input.<!-- Display form submission status -->
<?php if (!empty($errors)): ?>
<div class="status-msg error">
<ul>
<?php foreach ($errors as $error): ?>
<li><?php echo htmlspecialchars($error); ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php elseif ($success): ?>
<div class="status-msg success">
<?php echo htmlspecialchars($success); ?>
</div>
<?php endif; ?>
<!-- Contact form fields -->
<form action="" method="post" enctype="multipart/form-data" autocomplete="off">
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" name="name" required placeholder="Your name" value="<?php echo htmlspecialchars($_POST['name'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" required placeholder="ex: your@email.com" value="<?php echo htmlspecialchars($_POST['email'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="subject">Subject</label>
<input type="text" id="subject" name="subject" required placeholder="Enter subject" value="<?php echo htmlspecialchars($_POST['subject'] ?? ''); ?>">
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" name="message" required placeholder="Type your message..."><?php echo htmlspecialchars($_POST['message'] ?? ''); ?></textarea>
</div>
<div class="form-group">
<label for="file">Attachment</label>
<input type="file" id="file" name="attachment" accept=".pdf,.doc,.docx,.jpg,.png,.jpeg">
</div>
<input type="submit" name="submit" value="Send Message">
</form>
The following PHP script processes the form submission, validates the input data, handles the file upload, and sends an email with the form data and the uploaded file as an attachment.
$_POST superglobal array.FILTER_VALIDATE_EMAIL filter.mail() function.Note: The following PHP code snippet should be placed at the top of the same file where the HTML form is located or in a separate PHP file that handles the form submission.
<?php
// Define admin email
$admin_email = "admin@example.com"; // Change to your admin email
// Initialize variables
$errors = [];
$success = "";
// Handle form submission
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['submit'])) {
// Name validation
$name = trim($_POST["name"] ?? "");
if (empty($name)) {
$errors['name'] = "Name is required.";
} elseif (!preg_match("/^[a-zA-Z\s]+$/", $name)) {
$errors['name'] = "Name can only contain letters and spaces.";
}
// Email validation
$email = trim($_POST["email"] ?? "");
if (empty($email)) {
$errors['email'] = "Email is required.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = "Invalid email format.";
}
// Subject validation
$subject = trim($_POST["subject"] ?? "");
if (empty($subject)) {
$errors['subject'] = "Subject is required.";
}
// Message validation
$message = trim($_POST["message"] ?? "");
if (empty($message)) {
$errors['message'] = "Message is required.";
}
// File validation
$attachment = $_FILES['attachment'] ?? null;
$allowed_types = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'image/jpeg', 'image/png'];
if ($attachment && $attachment['error'] !== 4) { // 4 = no file uploaded
if ($attachment['error'] !== 0) {
$errors['attachment'] = "Error uploading file.";
} elseif (!in_array($attachment['type'], $allowed_types)) {
$errors['attachment'] = "Invalid file type. Allowed: PDF, DOC, DOCX, JPG, PNG.";
} elseif ($attachment['size'] > 5 * 1024 * 1024) {
$errors['attachment'] = "File size must be less than 5MB.";
}
}
// If no errors, send email
if (empty($errors)) {
$boundary = md5(time());
$headers = "From: {$name} <{$email}>\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
// HTML email body
$htmlContent = '
<html>
<head>
<style>
body { font-family: Arial, sans-serif; color: #333; }
.email-container { background: #f9f9f9; padding: 24px; border-radius: 8px; }
.email-header { font-size: 1.2rem; font-weight: bold; margin-bottom: 12px; color: #007bff; }
.email-row { margin-bottom: 10px; }
.email-label { font-weight: bold; color: #555; }
.email-message { margin-top: 18px; }
</style>
</head>
<body>
<div class="email-container">
<div class="email-header">New Contact Form Submission</div>
<div class="email-row"><span class="email-label">Name:</span> ' . htmlspecialchars($name) . '</div>
<div class="email-row"><span class="email-label">Email:</span> ' . htmlspecialchars($email) . '</div>
<div class="email-row"><span class="email-label">Subject:</span> ' . htmlspecialchars($subject) . '</div>
<div class="email-message"><span class="email-label">Message:</span><br>' . nl2br(htmlspecialchars($message)) . '</div>
</div>
</body>
</html>
';
// Multipart message
$body = "--{$boundary}\r\n";
$body .= "Content-Type: text/html; charset=UTF-8\r\n";
$body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
$body .= $htmlContent . "\r\n";
// Attachment
if ($attachment && $attachment['error'] === 0) {
$file_content = chunk_split(base64_encode(file_get_contents($attachment['tmp_name'])));
$file_name = basename($attachment['name']);
$file_type = $attachment['type'];
$body .= "--{$boundary}\r\n";
$body .= "Content-Type: {$file_type}; name=\"{$file_name}\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"{$file_name}\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= $file_content . "\r\n";
}
$body .= "--{$boundary}--";
// Send email
if (mail($admin_email, "Contact Form: " . $subject, $body, $headers)) {
$success = "Your message has been sent successfully!";
// Clear form data
$_POST = [];
} else {
$errors['form'] = "Failed to send your message. Please try again later.";
}
}
}
?>
Notes:
$admin_email variable to your desired recipient email address.mail() function. If you are using a local server (like XAMPP, WAMP, etc.), you may need to set up an SMTP server or use a third-party email service.upload_max_filesize and post_max_size settings.$_SERVER["REQUEST_METHOD"] == "POST".$_POST superglobal array and sanitize it using htmlspecialchars() to prevent XSS attacks.$_FILES superglobal array. We check for errors, validate the file type and size, and move the uploaded file to a designated directory on the server.mail() function to send the email with or without the attachment based on whether a file was uploaded.Contact Form Popup with Email using Ajax and PHP
Our example code helps you to add a contact form with email sending and file attachment functionality on the website using PHP. But you can use this code for any type of web form to send form data through email with a file attachment. In the example code, we have allowed only .pdf, .doc, .docx, and Image files as attachments. You can specify any type of file to upload and send it with the email on form submission.
Looking for expert assistance to implement or extend this script’s functionality? Submit a Service Request
💰 Budget-friendly • 🌍 Global clients • 🚀 Production-ready solutions
Hi, I am using the code above and tried your demo, however after I complete the form on my host-page and upload the file, click submit, I get the following messag on the form:
Sorry, there was an error uploading your file
I am uploading an accepted type .jpg – Can you please assist with why this is coming up?
Thanks,
Rod
Hi
I tried to use your source code contact-form on localhost.
I get this message:
Warning: mail(): Failed to connect to mailservfer al localhost port 25, verify your SMTP and smtp_port setting in php.ini or use ini_set()
Please, what can I do ?
Franco
The PHP default mail() function will not work on localhost. You need to check the email functionality on the hosting server.
How to stop refresh after submit
I understand that the recipient is me, so I’d replace admin@example.com with my email address. But everyone who uses the form will have a different name and a different email address, so what would I replace sender@example.com with in the $from entry and CodeWorld with in the $fromName entry?
Yes, you need to specify the sender name in the
$fromNamevariable and sender email in the$fromvariable.Hi,
How do I add file size limit to attachment?
Kindly suggest.
Excellent script.
But to send more than one attachment, how can you modify it?
Thanks
This tutorial will help you – https://www.codexworld.com/send-email-with-multiple-attachments-php/
form works but how can i have it upload more than one file at a time?
form works but how can i have it upload more than one file at a time?
Thanks man. your tutorial helped me. Thanks.
it’s working fine thanks for this
how can i add recaptcha V2 to this form ?
How to add CC
nice it is working properly
Lifesaver!