Simple PHP Mailer

24 Apr, 2009 PHP

Sometimes the most simple problems are the ones that developers have the hardest time with and it seems like those are the most frustrating. So in an effort to save developers hard times with some of the most simple things we are posting solutions to seemingly simple problems here.

This is a script that will generate an e-mail in PHP, and unlike other sites we are going to post the WHOLE solution here.

So here goes the code and the complete PHP file is attached….

Place this at the very top of your PHP file (and make sure it has a .php extension)


<?php

if(array_key_exists('btnSubmit', $_POST)) {

$to = "you@yourdomain.com";
$from = $_POST['txtemail'];
$subject = "A Message From Your Contact Page";
$phone = $_POST['txtphone'];
$fromname = $_POST['txtname'];
$comments = $_POST['txtcomments'];

$message = "$fromname\n";
$message .= "$phone\n";
$message .= "$from\n\n";
$message .= "$comments";

$additionalHeaders = "From: $fromname<$from>";

$mailSent = mail($to, $subject, $message, $additionalHeaders);
}

?>

That is all there is to the PHP part, now for the form…

Inside your body tags of course place the following code….


<form name="contact" action="#" method="post" class="con">
<label>Name</label>
<input type="text" name="txtname" class="txtbox" />
<label>Email</label>
<input type="text" name="txtemail" class="txtbox" />
<label>Phone Number</label>
<input type="text" name="txtphone" class="txtbox" />
<label>Comments</label>
<textarea name="txtcomments" cols="" rows=""></textarea>
<input type="submit" name="btnSubmit" value="" class="submit" />
<a href="javascript:document.contact.reset();"><img src="images/btn_reset.gif" alt="reset" class="reset"/></a>
</form>

1 Comment for this entry

  • contract warehousing, July 13th, 2009 on 4:26 pm

    I’ve recently started a blog, the information you provide on this site has helped me tremendously. Thank you for all of your time & work.