contactform.phps 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * This example shows how to handle a simple contact form.
  4. */
  5. $msg = '';
  6. //Don't run this unless we're handling a form submission
  7. if (array_key_exists('email', $_POST)) {
  8. date_default_timezone_set('Etc/UTC');
  9. require '../PHPMailerAutoload.php';
  10. //Create a new PHPMailer instance
  11. $mail = new PHPMailer;
  12. //Tell PHPMailer to use SMTP - requires a local mail server
  13. //Faster and safer than using mail()
  14. $mail->isSMTP();
  15. $mail->Host = 'localhost';
  16. $mail->Port = 25;
  17. //Use a fixed address in your own domain as the from address
  18. //**DO NOT** use the submitter's address here as it will be forgery
  19. //and will cause your messages to fail SPF checks
  20. $mail->setFrom('from@example.com', 'First Last');
  21. //Send the message to yourself, or whoever should receive contact for submissions
  22. $mail->addAddress('whoto@example.com', 'John Doe');
  23. //Put the submitter's address in a reply-to header
  24. //This will fail if the address provided is invalid,
  25. //in which case we should ignore the whole request
  26. if ($mail->addReplyTo($_POST['email'], $_POST['name'])) {
  27. $mail->Subject = 'PHPMailer contact form';
  28. //Keep it simple - don't use HTML
  29. $mail->isHTML(false);
  30. //Build a simple message body
  31. $mail->Body = <<<EOT
  32. Email: {$_POST['email']}
  33. Name: {$_POST['name']}
  34. Message: {$_POST['message']}
  35. EOT;
  36. //Send the message, check for errors
  37. if (!$mail->send()) {
  38. //The reason for failing to send will be in $mail->ErrorInfo
  39. //but you shouldn't display errors to users - process the error, log it on your server.
  40. $msg = 'Sorry, something went wrong. Please try again later.';
  41. } else {
  42. $msg = 'Message sent! Thanks for contacting us.';
  43. }
  44. } else {
  45. $msg = 'Invalid email address, message ignored.';
  46. }
  47. }
  48. ?>
  49. <!DOCTYPE html>
  50. <html lang="en">
  51. <head>
  52. <meta charset="UTF-8">
  53. <title>Contact form</title>
  54. </head>
  55. <body>
  56. <h1>Contact us</h1>
  57. <?php if (!empty($msg)) {
  58. echo "<h2>$msg</h2>";
  59. } ?>
  60. <form method="POST">
  61. <label for="name">Name: <input type="text" name="name" id="name"></label><br>
  62. <label for="email">Email address: <input type="email" name="email" id="email"></label><br>
  63. <label for="message">Message: <textarea name="message" id="message" rows="8" cols="20"></textarea></label><br>
  64. <input type="submit" value="Send">
  65. </form>
  66. </body>
  67. </html>