Gửi email có tệp đính kèm khi gửi biểu mẫu bằng JavaScript

Trong hướng dẫn này, bạn sẽ tìm hiểu cách tạo biểu mẫu liên hệ gửi email PHP có tệp đính kèm bằng cách sử dụng hàm PHP mail(). Hướng dẫn này sẽ chỉ cho bạn cách thực hiện điều đó bằng cách sử dụng hàm PHP mail(). Đây là một cách nhanh chóng và dễ dàng để tạo tệp đính kèm trong email bằng PHP

Mã miễn phí hiện có sẵn trên trang web này. Chúng tôi không lưu trữ bất kỳ thông tin nào của bạn và mã có sẵn với thiết kế cơ bản

PHP Gửi email có tệp đính kèm

Đây là một hướng dẫn về biểu mẫu liên hệ đơn giản sẽ chỉ cho bạn cách tạo biểu mẫu liên hệ PHP và gửi nó tới email có tệp đính kèm khi gửi biểu mẫu. Giờ đây, biểu mẫu sẽ cho phép bạn đính kèm nhiều định dạng tệp mà người dùng có thể đính kèm các định dạng tệp như tệp PDF, DOC, JPG, JPEG và PNG

Chúng tôi sẽ tạo một biểu mẫu liên hệ với tùy chọn đính kèm tệp sẽ gửi email đến một địa chỉ email cụ thể khi gửi biểu mẫu. Tôi chia mã thành ba phần để hiểu rõ hơn. Chúng tôi sẽ đặt mã HTML vào phần đầu tiên, sau đó là mã CSS trong tệp thứ hai và cuối cùng, chúng tôi sẽ đặt mã PHP

Làm cách nào để tạo email biểu mẫu PHP có tệp đính kèm?

Thực hiện theo các bước sau để Gửi Email có tệp đính kèm khi Gửi Biểu mẫu bằng PHP

  1. Tạo một biểu mẫu liên hệ HTML đơn giản (với CSS tùy chọn) và nhúng nó vào trang web của bạn
  2. Lưu trữ biểu mẫu liên hệ của bạn tới bất kỳ máy chủ lưu trữ web internet nào
  3. Kết nối trình chỉnh sửa mã của bạn với máy chủ từ xa để chỉnh sửa tập lệnh PHP
  4. Viết một tập lệnh PHP sẽ xử lý hiệu quả việc gửi email
  5. Nhận dữ liệu biểu mẫu đã gửi bằng cách sử dụng $_POST trong PHP
  6. Xác thực dữ liệu biểu mẫu để kiểm tra xem các trường bắt buộc có trống không
  7. Xác thực địa chỉ email bằng FILTER_VALIDATE_EMAIL trong PHP
  8. Kiểm tra phần mở rộng tệp để cho phép các định dạng tệp nhất định (tệp PDF, Hình ảnh và MS Word)
  9. Gửi thư trả lời tự động cho người dùng, cho họ biết chúng tôi sẽ xử lý yêu cầu của họ

Video hướng dẫn (Quy trình từng bước)

Cách tạo biểu mẫu liên hệ qua email PHP với tệp đính kèm

cũng đọc. Cách nhận Email từ biểu mẫu HTML bằng PHP

mã nguồn

Bây giờ bạn sẽ nhận được mã nguồn để tạo Biểu mẫu liên hệ gửi email PHP với tệp đính kèm

Biểu mẫu liên hệ HTML (Mã nguồn)

Trước hết, Tạo một chỉ mục tệp mới. php và dán mã biểu mẫu liên hệ HTML đã cho vào đó

<?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>

Đầu ra biểu mẫu liên hệ

Gửi email có tệp đính kèm khi gửi biểu mẫu bằng JavaScript
Biểu mẫu liên hệ PHP gửi email có tệp đính kèm

Mã nguồn CSS

Tiếp theo, tạo một phong cách mới. css và dán mã biểu mẫu liên hệ CSS bên dưới

*{
  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;
}

Biểu mẫu liên hệ PHP Gửi email (Mã nguồn)

Cuối cùng bên dưới là đoạn mã PHP của biểu mẫu liên hệ HTML để gửi dữ liệu biểu mẫu liên hệ đến 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 = '[email protected]';

                // 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.';
    }
}

Từ cuối cùng

Bài viết trên blog này đã giải thích cho bạn cách tạo biểu mẫu người dùng đang hoạt động bằng cách sử dụng PHP với chức năng đính kèm và gửi email từ phía máy khách bằng cách sử dụng chức năng gửi thư PHP. Nếu bạn cảm thấy khó hiểu bài viết này, bạn có thể hỏi trong phần bình luận bên dưới. Đề xuất và truy vấn của bạn luôn được chào đón. Nếu thấy hữu ích đừng quên SUBSCRIBE kênh YouTube của mình nhé