contact.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. require 'vendor/autoload.php'; // if you used Composer
  3. use PHPMailer\PHPMailer\PHPMailer;
  4. use PHPMailer\PHPMailer\Exception;
  5. $mail = new PHPMailer(true);
  6. try {
  7. $name = htmlspecialchars($_POST['name'] ?? '');
  8. $email = htmlspecialchars($_POST['email'] ?? '');
  9. $phone = htmlspecialchars($_POST['phone'] ?? '');
  10. $pref = htmlspecialchars($_POST['preferred_contact'] ?? '');
  11. $message = htmlspecialchars($_POST['message'] ?? '');
  12. if (!$name || !$email || !$phone || !$pref || !$message) {
  13. http_response_code(400);
  14. echo "All fields are required.";
  15. exit;
  16. }
  17. if (!empty($_POST['website'])) {
  18. // Bot filled out the honeypot
  19. http_response_code(400);
  20. die("Bot detected. Submission rejected.");
  21. }
  22. $body = <<<EOT
  23. You have a new contact form submission:
  24. Name: $name
  25. Email: $email
  26. Phone: $phone
  27. Preferred Contact: $pref
  28. Message:
  29. $message
  30. EOT;
  31. // SMTP config
  32. $dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
  33. $dotenv->load();
  34. $mail->isSMTP();
  35. $mail->Host = $_ENV['SMTP_HOST'];
  36. $mail->SMTPAuth = true;
  37. $mail->Username = $_ENV['SMTP_USER'];
  38. $mail->Password = $_ENV['SMTP_PASS'];
  39. $mail->SMTPSecure = $_ENV['SMTP_SECURE'];
  40. $mail->Port = $_ENV['SMTP_PORT'];
  41. // Email headers
  42. $mail->setFrom($_ENV['MAIL_TO'], $name); // sender = SMTP account
  43. $mail->addAddress($_ENV['MAIL_TO']); // recipient
  44. $mail->addReplyTo($email, $name); // visitor’s email
  45. $mail->Subject = 'New Contact Form Submission From Company Site';
  46. $mail->Body = $body;
  47. $mail->send();
  48. echo "OK";
  49. } catch (Exception $e) {
  50. http_response_code(500);
  51. echo "Mailer Error: " . $mail->ErrorInfo;
  52. }