PHP Forums Archive

PHP mail script

Tags: contact form, form, mail header

Olaf posted on 2009-09-16 21:34:45 #

This short snippet will process your whole contact form. Just use the code in your (external) script and change the mail address. Tip: Use clear field names in your form.

<?php
$goto_after_mail = "thanks.htm"; // this is the page which is shown after the mail is submitted
$from_mail = $_REQUEST['from_email'];
$from_name = $_REQUEST['from_name']; // use both value's from your form
$header = "From: \"$from_name\" <$from_mail>\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n";
$subject = "Your webform posted at ".date("d-m-Y"); //your mailsubject incl. current date
foreach ($_REQUEST as $key => $val) {
    if ($key != "from_email" && $key != "from_name") { //skip, this values are already in the header
        $body .= $key . " : " . $val . "\r\n";
    }
}
if (mail("you@yourmail.com", $subject, $body, $header)) {
	header("Location: ".$goto_after_mail);
        exit;
}
?>

Later updates:
I noticed that some junk mail controls identifies messages send with this script as spam. I changed the headers a little bit to solve this problem. The header location function is only used now if the mail is posted successfully.

Comments / discussions

Olaf posted on 2009-09-16 21:38:16 #

Note, this is a snippet we have published a few years ago (in times with less spam), we suggest these days to send mails by mature php scripts like phpmailer. Anyway this example shows how-to process a standard form as well.