PHP mail() Function

The PHP mail() function is handy. You can use it to have people contact you through a form on your Web page if you don’t feel comfortable displaying your email address. The sample code below will send an email to “contact@mydomain.com” with the subject and message as the respective text inputs below.

  1. <?php
  2. // check to see if send button has been clicked
  3. if (isset($_REQUEST["submit"])) {
  4.  
  5. 	$to = "contact@mydomain.com";
  6. 	$from = $_REQUEST["email"];
  7. 	$subject = $_REQUEST["subject"];
  8. 	$message = $_REQUEST["message"];
  9.  
  10. 	// validate email address
  11. 	if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
  12. 		$err_from = true;
  13. 	}
  14.  
  15. 	if ($err_from) {
  16. 		// error message goes here
  17. 	} else {
  18. 		// try to send it
  19. 		if (mail($to, $subject, $message, "From: $from")) {
  20. 			// message has been sent
  21. 		} else {
  22. 			// there's been an error
  23. 		}
  24. 	}
  25. }
  26. ?>
  27. <form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
  28. 	<p><label>From:<br /><input name="email" type="text" value="<?php echo $from; ?>" /></label></p>
  29. 	<p><label>Subject:<br /><input name="subject" type="text" value="<?php echo $subject; ?>" /></label></p>
  30. 	<p><label>Message:<br /><textarea name="message" rows="10"><?php echo $message; ?></textarea></label></p>
  31. 	<p><input name="submit" type="submit" value="Send" /></p>
  32. </form>

See it live.

Posted in PHP Tutorials | Tagged as ,

Leave a Reply