· 8 years ago · Mar 23, 2018, 10:30 PM
1<?php
2/*
3THIS FILE USES PHPMAILER INSTEAD OF THE PHP MAIL() FUNCTION
4*/
5
6require 'PHPMailer-master/PHPMailerAutoload.php';
7
8/*
9* CONFIGURE EVERYTHING HERE
10*/
11// an email address that will be in the From field of the email.
12$fromEmail = 'demo@user.com';
13$fromName = 'Demo contact form';
14
15// an email address that will receive the email with the output of the form
16$sendToEmail = 'demo@user.com';
17$sendToName = 'Demo contact form';
18
19// subject of the email
20$subject = 'New message from contact form';
21
22// form field names and their translations.
23// array variable name => Text to appear in the email
24$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message');
25
26// message that will be displayed when everything is OK :)
27$okMessage = 'Contact form successfully submitted. Thank you, I will get back to you soon!';
28
29// If something goes wrong, we will display this message.
30$errorMessage = 'There was an error while submitting the form. Please try again later';
31
32/*
33* LET'S DO THE SENDING
34*/
35
36// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
37error_reporting(E_ALL & ~E_NOTICE);
38
39try
40{
41
42 if(count($_POST) == 0) throw new \Exception('Form is empty');
43
44 $emailTextHtml = "<h1>You have a new message from your contact form</h1><hr>";
45 $emailTextHtml .= "<table>";
46
47 foreach ($_POST as $key => $value) {
48 // If the field exists in the $fields array, include it in the email
49 if (isset($fields[$key])) {
50 $emailTextHtml .= "<tr><th>$fields[$key]</th><td>$value</td></tr>";
51 }
52 }
53 $emailTextHtml .= "</table><hr>";
54 $emailTextHtml .= "<p>Have a nice day,<br>Best,<br>Ondrej</p>";
55
56 $mail = new PHPMailer;
57
58 $mail->setFrom($fromEmail, $fromName);
59 $mail->addAddress($sendToEmail, $sendToName); // you can add more addresses by simply adding another line with $mail->addAddress();
60 $mail->addReplyTo($from);
61
62 $mail->isHTML(true);
63
64 $mail->Subject = $subject;
65 $mail->msgHTML($emailTextHtml); // this will also create a plain-text version of the HTML email, very handy
66
67
68 if(!$mail->send()) {
69 throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
70 }
71
72 $responseArray = array('type' => 'success', 'message' => $okMessage);
73}
74catch (\Exception $e)
75{
76 // $responseArray = array('type' => 'danger', 'message' => $errorMessage);
77 $responseArray = array('type' => 'danger', 'message' => $e->getMessage());
78}
79
80
81// if requested by AJAX request return JSON response
82if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
83 $encoded = json_encode($responseArray);
84
85 header('Content-Type: application/json');
86
87 echo $encoded;
88}
89// else just display the message
90else {
91 echo $responseArray['message'];
92}