Text to appear in the email
$fields = array('name' => 'Name', 'surname' => 'Surname', 'phone' => 'Phone', 'email' => 'Email', 'message' => 'Message', 'department' => 'Department');
/*
* LET'S DO THE SENDING
*/
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailTextHtml .= "
";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailTextHtml .= "| $fields[$key] | $value |
";
}
}
$emailTextHtml .= "
";
$mail = new PHPMailer;
$mail->setFrom($fromEmail, $fromName);
$mail->addAddress($sendToEmail, $sendToName);
$mail->addReplyTo($from);
$mail->isHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = $subject;
$mail->Body = $emailTextHtml;
$mail->msgHTML($emailTextHtml);
if($smtpUse == true) {
// Tell PHPMailer to use SMTP
$mail->isSMTP();
// Enable SMTP debugging
// 0 = off (for production use)
// 1 = client messages
// 2 = client and server messages
$mail->Debugoutput = function ($str, $level) use (&$mailerErrors) {
$mailerErrors[] = [ 'str' => $str, 'level' => $level ];
};
$mail->SMTPDebug = 3;
$mail->SMTPAuth = true;
$mail->SMTPSecure = $smtpSecure;
$mail->SMTPAutoTLS = $smtpAutoTLS;
$mail->Host = $smtpHost;
$mail->Port = $smtpPort;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
}
if(!$mail->send()) {
throw new \Exception('I could not send the email.' . $mail->ErrorInfo);
}
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e) {
$responseArray = array('type' => 'danger', 'message' => $e->getMessage());
}
// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
}
// else just display the message
else {
echo $responseArray['message'];
}