drilix.com

Freedom, Community & Sustainability

PHP: send e-mail forms

January 2, 2011 -- William
Last modified on August 2016
Duration: 5 minutes or less

-Simple way to send e-mails from your site with a php function-

The PHP mail function can be very handy for a variety of tasks. The most obvious one is to allow visitors to send you e-mails through a form on your site. But you can also use e-mail to alert you about what's going on in your site.

As a starter, I just want to mention that you can trigger e-mails from the site through a mail program like thunderbird but it relies on the user having such mail program installed and configured on their machine. That's how to do it:


<a href="mailto:me@mydomain.com">Send me an 
email</a>

If you want to send the mail directly from your server you can use the PHP built-in mail function. You can paste this code in an empty file, name it and give it a .php extension. Whenever you call this file, an email will be sent to a chosen mail address. In this example the variables $to, $subject and $message are hard coded but you can enter them dynamically.


<?php
$to = 'your@e-mail.com';
$subject = 'What is's about';
$message = 'This is my message';
mail($to, $subject, $message);
?>

What you need to do is personalize what's between brackets with your own information. The best thing is to use variables and let the user define the subject and the message. They can do that through a form.

The form

You could build any form you want with any information you want. I'm just going to put here a standard form, like most e-mails, with subject and message. Paste this into an html page where the form should be.


<form method="post" action="send_it.php">
<input type="hidden" name="subject" value="userfeedback" />
<table align="center">
<tr>
  <td>E-mail:</td>
  <td> <input type="text" name="email" size="30" /> </td>
</tr>
<tr>
  <td colspan="2"><p>Message:</p>
  <textarea cols="50" rows="6" name="message"></textarea>
  </td>
</tr>
</table>
<br />
<input type="submit" value="Send" />
<input type="reset" value="Cancel" />
</form>

This form points to a file named sent_it.php. This file contains the php mail function mentioned before. So the file send_it.php should look like explained below:

Treating the form


<?php
foreach ($_POST as $var => $value) {
    $$var = $value;
}
mail('your@e-mail.com', '$subject', '$message', '$email');
header("Location: thankyou.php");
?>

Finally, this page points to a "thank you" page to show that everything went alright. This is only a suggestion and my hope is that with one simple example you can get to know how it works. Then you could use this code in a variety of ways like for example to tell you through an email when someone reached a certain page or performed a certain action. Even more useful than that is to receive by mail the error log when a bug happens on your site... your user don't even need to know about it!

Add new comment