A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Code Snippets > PHP > Send Email Submit one!

Send Email

1) HTML Form with Inputs

<form action="" method="post">
  <label for="Name">Name:</label>
  <input type="text" name="Name" id="Name" />

  <label for="Email">Email:</label>
  <input type="text" name="Email" id="Email" />

  <label for="Message">Message:</label><br />
  <textarea name="Message" rows="20" cols="20" id="Message"></textarea>

  <input type="submit" name="submit" value="Submit" />
</form>

2) Process with PHP

This could be in a seperate file (e.g. sendemail.php) in which you’d set the action URL of the form to go there. Or, have the form submit to itself (leave action URL blank) and test for one of the values of the form being POSTed and process there.

<?php
       // from the form
       $name = trim(strip_tags($_POST['name']));
       $email = trim(strip_tags($_POST['email']));
       $message = htmlentities($_POST['message']);

       // set here
       $subject = "Contact form submitted!";
       $to = 'your@email.com';

       $body = <<<HTML
$message
HTML;

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanks.html');
?>

3) Test it

And make sure to keep up with security news around the web.

9 Responses

  1. thanks this was real helpful !
    as I’m quite new to PHP.

  2. Andy Jones says:

    Hiya – great stuff as always – but for some reason, I can’t get this to work! It redirects to me thanks page, but the email doesn’t come through. Is there something special that has to be configured in php? I’m running php4 (but I don’t really get too involved in php stuff!!)

    Lovin your work on twitter by the way!

  3. imeera says:

    great! – but for some reason, It redirects to me thanks page, but the email comes blank no data in there. any help would be appreciated. I am getting in to php.

  4. Leon says:

    Thanks Chris, it is really helpfull

  5. Blair says:

    still can’t get this to work. using wordpress.

  6. Blair says:

    I get this error: Warning: Cannot modify header information – headers already sent by (output started at /home2/yourmedp/public_html/wp-content/themes/obvious/inc/contact-form.php:3) in /home2/yourmedp/public_html/wp-content/themes/obvious/inc/contact-form.php on line 24

  7. varun says:

    Can U Tell Me Solution For Bulk Mail ??

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.