DEV Community

Cover image for How to Create PHP Send Email Contact Form with Attachment
HMA WebDesign
HMA WebDesign

Posted on

How to Create PHP Send Email Contact Form with Attachment

We are going to create aPHP Send Email Contact Form with Attachment option which will send an email to a specific email address on form submission.

I divided the code into three parts for better understanding. We will put the HTML code in the first part, then the CSS code in the second file, and at the end, we will put the PHP code.

How do I create a PHP form email with an attachment?

Follow these steps to Send an Email with an attachment on Form Submission using PHP:

  1. Build a simple HTML contact form (with optional CSS) and embed it on your website.
  2. Host your contact form to any internet web hosting server.
  3. Connect your code editor to a remote server to edit the PHP script.
  4. Write a PHP script that will effectively handle sending emails.
  5. Get the submitted form data using $_POST in PHP.
  6. Validate form data to check whether the mandatory fields are not empty.
  7. Validate email address using FILTER_VALIDATE_EMAIL in PHP.
  8. Check the file extension to allow certain file formats (PDF, Image, and MS Word files)
  9. Send an autoresponder to a user, letting them know we’ll handle their request .

Video Tutorial (Step-by-Step Process)

Source Codes

Now you will get the source codes to create PHP Send Email Contact Form with attachment.

HTML Contact Form (Source Code)
First of all, Create a new file index.php and paste the given HTML contact form code there!

<?php include 'mail.php' ?>

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">

 <!-- Linking CSS file -->
 <link rel="stylesheet" href="style.css">
 <title>Document</title>
</head>

<body>
 <div class="container">


  <form method="post" class="form" enctype="multipart/form-data">
   <div class="heading">
    <h2>Contact Form
     <h2 />
   </div>

   <div class="formGroup">
    <input type="text" name="name" id="name" placeholder="Name" autocomplete="off" value="<?php echo !empty($postData['name']) ? $postData['name'] : ''; ?>" required="">
   </div>

   <div class="formGroup">
    <input type="email" name="email" id="email" placeholder="Email ID" autocomplete="off" value="<?php echo !empty($postData['email']) ? $postData['email'] : ''; ?>" required="">
   </div>

   <div class="formGroup">
    <input type="text" name="subject" placeholder="Subject" autocomplete="off" value="<?php echo !empty($postData['subject']) ? $postData['subject'] : ''; ?>" required="">
   </div>

   <div class="formGroup">
    <input type="text" name="message" placeholder="Your Message" autocomplete="off" <?php echo !empty($postData['message']) ? $postData['message'] : ''; ?> required="">
   </div>

   <div class="formGroup">
    <input type="file" name="attachment" class="form-control" multiple>
   </div>

   <!-- Display submission status -->
   <div class="status">
    <?php if (!empty($statusMsg)) { ?>
     <p class="statusMsg <?php echo !empty($msgClass) ? $msgClass : ''; ?>">
      <?php echo $statusMsg; ?></p>
    <?php } ?>
   </div>

   <div class="formGroup">
    <button class="btn2" name="submit" value="SUBMIT" type="submit">SUBMIT </button>
   </div>

   <form />
 </div>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

CSS Source Code

Next, create a new style.css file and paste the below CSS contact form code.

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
/* adding background image */
body{
  font-family: Arial, Helvetica, sans-serif;
}
/* Center content vertically and horizontally */
.container{
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.form{
  width: 350px;
  height: 460px;
  background-color: white;
  box-shadow: 0 5px 30px black;
}
.heading h2{
  padding: 3px;
  margin: 30px 0px 10px 30px;
  border-style: none;
  background-color: transparent;
  color: black;
  font-size: 20px;
  font-weight: 600;
}
.formGroup{
  display: flex;
  justify-content: center;
}
.formGroup input{
  border: none;
  width: 80%;
  padding: 7px;
  margin-bottom: 15px;
  background-color: transparent;
  border-bottom: 2px solid rgb(68, 68, 68);
  color: black;
  font-weight: bold;
  font-size: 14px;
}

input:focus{
  outline: none;
  font-size: 17px;
  background-color: transparent;
}
.text{
  color: rgb(42, 41, 41);
  font-size: 13px;
}
.btn2{
  padding: 10px;
  outline: none;
  width: 150px;
  border-radius: 20px;
  border-style: none;
  background-color: rgb(28, 131, 28);
  color: whitesmoke;
  font-weight: 600;
  margin-top: 10px;
}
.btn2:hover {
 background-color: rgb(1, 63, 1);
}
.status {
 color: green;
 text-align: center;
 margin: 5px;
 font-weight: 600;
}
Enter fullscreen mode Exit fullscreen mode

PHP Contact Form Send Email (Source Code)

Finally below is the PHP code script of the HTML contact form to send contact form data to email.

<?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 Email, write your email here
                $toEmail = 'YourEmail@email.com';

                // Sender Data
                $from = $email;
                $fromName = $name;

                // Subject
                $emailSubject = 'Contact Request Submitted by '.$name;

                // Message 
                $htmlContent = '<h2>Customer Contact Detail!</h2>
                    <p><b>Name:</b> '.$name.'</p>
                    <p><b>Email:</b> '.$email.'</p>
                    <p><b>Subject:</b> '.$subject.'</p>
                    <p><b>Message:</b> '.$message.'</p>';

                // 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 Message was submitted successfully!';
                    $msgClass = 'succdiv';

                    $postData = '';
                }else{
                    $statusMsg = 'Your contact request submission failed, please try again.';
                }
            }
        }
    }else{
        $statusMsg = 'Please fill all the fields.';
    }
}
Enter fullscreen mode Exit fullscreen mode

Final Words
This blog article explained to you, how to create a working user form using PHP with an attachment function and send an email from the client side using the PHP mailer function. If you feel any difficulty understanding this post, you can ask in the comment section below. Your suggestion and queries are always welcome. If you find it helpful don’t forget to SUBSCRIBE to my YouTube Channel.

Top comments (2)

Collapse
 
feyissa_mustefa_7dfdcd9d5 profile image
Feyissa Mustefa

asshole

Collapse
 
dhaval_akbari_c9e717b2239 profile image
dhaval akbari

Your contact request submission failed, please try again.