How to send email using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to send email using PHP

Post by Tony » Sun Nov 29, 2009 3:43 am

Here is a simple Form Mail script. It can be used on your website for people sending you messages, rather than using an email link. The script provides a form with name, email address, and message. It validates the email address format. It also provides some protection against mail bombing by only allowing 3 messages to be sent from a single browser session. You can easily modify the script to fit the theme of your site, or change the form.

Code: Select all

<?php
// modify the two lines below
$emailAddress = "[email protected]";  // your email address
$thankyouPage = "";  // put in a url (or relative page) to go to a Thank You page
// modify the two lines above
session_start();
if (!empty($_POST)) {
  foreach ($_POST as $key=>$value) {
      $_POST[$key] = stripslashes($_POST[$key]);
    $_POST[$key] = htmlspecialchars($_POST[$key],ENT_QUOTES);
  }
}
if (isset($_POST['send']) AND isset($_SESSION['msgCount'])) {
  if (!preg_match("(^[-\w\.]+@([-a-z0-9]+\.)+[a-z]{2,4}$)i",$_POST['email'])) $alert = "You have entered an invalid email address.";
  if ($_SESSION['msgCount'] >= "3") $alert = "Only 3 messages can be sent per session.";
  if (empty($alert)) {
    $_SESSION['msgCount']++;
    putenv('TZ=EST5EDT'); // eastern time
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= "From: <".$_POST['email'].">\r\n";
    $message = "<table cellpadding='5' border='1'>";
    foreach ($_POST as $key => $value)
      if (!preg_match("(^send)",$key)) {
        $value = wordwrap($value,65,"<br />");
        $message .="<tr><td><b>$key</b></td><td>$value</td></tr>";
      }
    $message .= "</table>";    
    $message .= "<br />Time of the message: ".date(" F d  h:ia")."<br />";
    $message .= "IP Address: ".$_SERVER['REMOTE_ADDR']."<br />";
    $message .= "Hostname: ".gethostbyaddr($_SERVER['REMOTE_ADDR'])."<br />";
    $subject = $_SERVER['HTTP_HOST']." Message";
    mail($emailAddress,$subject,$message,$headers);
    if (!empty($thankyouPage)) {
      header('location: '.$thankyouPage);
      die();
    }
    unset($_POST);
    $alert = "Your message has been sent.";
  }
}
if (!isset($_SESSION['msgCount'])) $_SESSION['msgCount'] = 0;
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['SCRIPT_NAME']; ?>">
<div style="text-align: center; width: 500px; margin: 50px auto 0px auto; border: solid 1px black;">
<br>
Send us a message<br><br>
your name<br><input type="text" style="width: 330px;" name="name" value="<?php echo $_POST['name']; ?>" maxlength="50"><br><br>
your email address<br><input type="text" style="width: 330px;" name="email" value="<?php echo $_POST['email']; ?>" maxlength="50"><br><br>
your message<br><textarea name="content" style="width: 330px; height: 100px;" rows="6" cols="80"><?php echo $_POST['content']; ?></textarea>
<br><br>
<input type="submit" name="send" value="submit">
<br /><br />&nbsp;
</div>
</form> 
<?php  if (isset($alert)) echo "<script type='text/javascript'>alert('$alert');</script>";  ?>
</body></html>
This script also has built-in bot protection. The mail bomb protection feature in this script uses a session variable which is set when the actual form is presented. Form processing will not happen (an email will not be sent) unless the form has been presented first (and the session variable set). Bots will initiate a new session on every access when trying to submit a form, so an email will not be sent. For further protection against bots (and to slow down users), consider incorporating CAPTCHA (which you can also find on this site).

In summary, the only thing you need to do is update the values in the first two lines if the script. The first line is your email address. The second one is the location of a "Thank You" page if you wish to use one.

If you want to add or change the form, just make the html changes following the method used for the current variables. The php script will put all $_POST variables in the email (except "send" which is the button). The only requirement is that there must be an input element named "email" (since that value is validated and used as the from address in the email).
Post Reply

Return to “PHP & MySQL”