article

Friday, January 3, 2020

Send Email with Attachment on Form Submission using PHP

Send Email with Attachment on Form Submission using PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
<!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>
<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