article

Friday, January 3, 2020

Send Email with Attachment on Form Submission using PHP

Send Email with Attachment on Form Submission using PHP
<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Send Email with Attachment on Form Submission using PHP</title> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style>.btn-danger {width:100%;}.btn-success {width:100%;}</style>
</head>
<body>
<?php
$postData = $uploadedFile = $statusMsg = '';
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 = '<p class="btn btn-danger">Please enter your valid email.</p>';
        }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 = "<p class='btn btn-danger'>Sorry, there was an error uploading your file.</p>";
                    }
                }else{
                    $uploadStatus = 0;
                    $statusMsg = '<p class="btn btn-danger">Sorry, only PDF, DOC, JPG, JPEG, & PNG files are allowed to upload.</p>';
                }
            }
   if($uploadStatus == 1){
                // Recipient
                $toEmail = $email;

                // Sender
                $from = 'raizen02102020@gmail.com';
                $fromName = 'Tutorial101 dot blogspot com';
                
                // Subject
                $emailSubject = 'Contact Request Submitted by '.$name;
                // Message 
                $htmlContent = '<h2>Contact Request Submitted</h2>
                    <p><b>Name:</b> '.$name.'</p>
                    <p><b>Email:</b> '.$email.'</p>
                    <p><b>Subject:</b> '.$subject.'</p>
                    <p><b>Message:</b><br/>'.$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 = '<p class="btn btn-success">Your contact request has been submitted successfully !</p>';
                    
                    $postData = '';
                }else{
                    $statusMsg = '<p class="btn btn-danger">Your contact request submission failed, please try again.</p>';
                }
            }

  } 
        
    }else{
        $statusMsg = '<p class="btn btn-danger">Please fill all the fields.</p>';
    }
}
?>
<div class="container">
    <div class="row">
  <p><h2>Send Email with Attachment on Form Submission using PHP</h2></p>
  <p><h3>Contact Us</h3></p>
        <div class="col-md-8">
            <div class="well well-sm">
    <!-- Display submission status -->
    <?php if(!empty($statusMsg)){ ?>
     <p class="statusMsg"><?php echo $statusMsg; ?></p>
    <?php } ?>
                <form method="post" action="" enctype="multipart/form-data" autocomplete="off" class="animate-form">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">Name</label>
       <input type="text" name="name" class="form-control" value="<?php echo !empty($postData['name'])?$postData['name']:''; ?>" placeholder="Enter name" required="required" />
                         </div>
                        <div class="form-group">
                            <label for="email">Email Address</label>
                            <div class="input-group">
                                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
                                <input type="email" name="email" class="form-control" placeholder="Enter email" required="required" /></div>
                        </div>
                        <div class="form-group">
                            <label for="subject">Subject</label>
                            <input type="text" name="subject" class="form-control" value="<?php echo !empty($postData['subject'])?$postData['subject']:''; ?>" placeholder="Subject" required=""/>
                        </div>
      <div class="form-group">
                            <input type="file" name="attachment" class="form-control">
                        </div>     
                    </div>
                    <div class="col-md-6">
                        <div class="form-group">
                            <label for="name">Message</label>
                            <textarea name="message" class="form-control" rows="11" cols="25" placeholder="Write your message here"/>
       <?php echo !empty($postData['message'])?$postData['message']:''; ?></textarea>
                        </div>
                    </div>
                    <div class="col-md-12">
      <input type="submit" name="submit" class="btn btn-primary pull-right" value="Send Message">
                    </div>
                </div>
                </form>
     <p style="font-size: 13px;margin-top: 5px;color: #F44949;">For testing purpose, the email will be sent to your given email address.</p>
            </div>
        </div>
        <div class="col-md-4">
            <form>
            <legend><span class="glyphicon glyphicon-globe"></span> Our office</legend>
            <address>
                <strong>Twitter, Inc.</strong><br>
                795 Folsom Ave, Suite 600<br>
                San Francisco, CA 94107<br>
                <abbr title="Phone">
                    P:</abbr>
                (123) 456-7890
            </address>
            <address>
                <strong>Full Name</strong><br>
                <a href="mailto:#">first.last@example.com</a>
            </address>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Related Post