Script 11.1 Sending Email

Focusing on the mail() function to send email from a submitted contact form.

Output

Say Hello

Contact Me

Source
<h1>Say Hello</h1>
<?php # Script 11.1 - email.php

// Check for form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Minimal form validation:
	if (!empty($_POST['name']) && !empty($_POST['email']) && !empty($_POST['comments']) ) {
	
		// Create the body:
		$body = "Name: {$_POST['name']}\n\nComments: {$_POST['comments']}\n\nEmail: {$_POST['email']}";

		// Make it no longer than 70 characters long:
		$body = wordwrap($body, 70);
	
		// Send the email - disabled to prevent future spam
		//mail('noreply@ashlietaylor.com', 'Script 11.1 Form Submission', $body, "From: {$_POST['email']}");

		// Print a message:
		echo '<div class="message">Thank you for submitting my form. I will never use your information - I promise!</div>';
		
		// Clear $_POST (so that the form's not sticky):
		$_POST = array();
	
	} else {
		echo '<p class="error">Please fill out the form completely.</p>';
	}
	
} // End of main isset() IF.

// Create the HTML form:
?>
<form action="" method="post">
	<fieldset><legend>Contact Me</legend>
		<p>
			<label for="n">Name: </label>
			<input type="text" id="n" name="name" size="30" maxlength="60" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>" />
		</p>
		<p>
			<label for="e">Email Address: </label>
			<input type="text" id="e" name="email" size="30" maxlength="80" value="<?php if (isset($_POST['email'])) echo $_POST['email']; ?>" />
		</p>
		<p>
			<label for="c">Comments: </label>
			<textarea id="c" name="comments" rows="5" cols="30"><?php if (isset($_POST['comments'])) echo $_POST['comments']; ?></textarea>
		</p>
		<p>
			<input type="submit" name="submit" value="Send!" />
		</p>
	</fieldset>
</form>