Subscribe to Tutorial Feed

Flash and PHP Bible

The Flash and PHP Bible has been released! The book can be found on Amazon or wherever fine books are sold in your area.

The Flash and PHP Bible has a forum for quick support.

Scriptplayground » tutorials » php » Basic Emailer with PHP

Basic Emailer with PHP

Basic PHP emailer with example form. Makes use of default mail functions in PHP.

This article explains a basic PHP emailer. We will start off with the HTML and then move on to the PHP.

HTML Form Code, place this in your HTML code for your page.

<form method="post" action="contact.php">
<input type="hidden" name="send" value="true" />
<br /><br />
<p>Your Name: <br />
<input name="name" type="text" id="name" />
</p>
<p>Your E-mail:<br />
<input name="email" type="text" id="email" />
</p>
<p>Your Questions/Comments:<br />
<textarea name="message" cols="40" rows="5" id="message"></textarea>
</p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>

That is a basic HTML Form with name, email, message fields, next up the PHP code. Name the PHP file "contact.php".

The first part is the configuration variables.

///////////////////////////
//Begin Configuration
///////////////////////////

// Your email
$to = "feedback@mkeefedesign.com" . ", " ;

// Email Subject
$subject = "Comment From " . "mkeefeDESIGN";

// Server name, to display in the headers
$server_name = "mkeefeDESIGN";

///////////////////////////
//End Configuration
///////////////////////////

Then we check to make sure the script should send an email, we do this by checking for a hidden value "send" in the HTML form

if (!empty($_POST['send']) || !empty($_GET['send']))
	{
	$action = (!empty($_POST['send'])) ? $_POST['send'] : $_GET['send'];
	}
else
	{
	$action = '';
	}

Assuming that the hidden value was set lets check that it had the right value "send" and build the email pieces

$build_message = false;
if($action != "")
	{
	$build_message = true;
	$message = trim($_POST['message']);
	$name = trim($_POST['name']);
	$email = trim($_POST['email']);
	$time = time();
	$date = date("F j, Y", time());
	$headers = "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
	$headers .= "From: $email\r\n";
	$headers .= "X-mailer: " . $server_name . " Server\r\n";
	}

Now lets build the actual email content

if($build_message)
	{
/* message */
$message = "
Sender Name: $name\n 
Sender E-Mail: $email\n 
Date Sent: $date\n 
Message:\n----------------------------------------\n$message \n";

	if(mail($to, $subject, $message, $headers))
		{
		$result = "<b>Thank you</b>.<br />I will get back to you very soon.<br />";
		}
	else
		{
		$result = "Sorry: An error occured, please try again later.";
		}
	}

Finally we send some sort of message to the user, to let them know whether the email was sent or not.

// Output a result Message
print $result;

Here is the code in full, enjoy.

<?
///////////////////////////
//Begin Configuration
///////////////////////////

// Your email
$to = "feedback@mkeefedesign.com" . ", " ;

// Email Subject
$subject = "Comment From " . "mkeefeDESIGN";

// Server name, to display in the headers
$server_name = "mkeefeDESIGN";

///////////////////////////
//End Configuration
///////////////////////////

if (!empty($_POST['send']) || !empty($_GET['send']))
	{
	$action = (!empty($_POST['send'])) ? $_POST['send'] : $_GET['send'];
	}
else
	{
	$action = '';
	}

$build_message = false;
if($action != "")
	{
	$build_message = true;
	$message = trim($_POST['message']);
	$name = trim($_POST['name']);
	$email = trim($_POST['email']);
	$time = time();
	$date = date("F j, Y", time());
	$headers = "MIME-Version: 1.0\r\n";
	$headers .= "Content-type: text/plain; charset=UTF-8\r\n";
	$headers .= "From: $email\r\n";
	$headers .= "X-mailer: " . $server_name . " Server\r\n";
	}

if($build_message)
	{
/* message */
$message = "
Sender Name: $name\n 
Sender E-Mail: $email\n 
Date Sent: $date\n 
Message:\n----------------------------------------\n$message \n";

	if(mail($to, $subject, $message, $headers))
		{
		$result = "<b>Thank you</b>.<br />I will get back to you very soon.<br />";
		}
	else
		{
		$result = "Sorry: An error occured, please try again later.";
		}
	}

// Output a result Message
print $result;
?>

That is the end of the article. I hope you have an understanding of how it all works, and now you can add contact forms to your pages.

Follow Scriptplayground on Twitter (@scriptplay)

Comments: Basic Emailer with PHP

 jamie  Thu Mar 15, 2007 1:36 pm  
where does the php coding go?
 jamie  Thu Mar 15, 2007 1:39 pm  
everytime i go to creat PHP page in dreamweaver this is what i get:





so where do the code go?

Untitled Document





 jamie  Thu Mar 15, 2007 1:52 pm  
hi i just copied and pasted your code (PHP) into the body bit of my php page, saved as contact.php. Try it out my website please, i dont have a clue whats wrong with it!
 mkeefe  Thu Mar 15, 2007 2:17 pm  
The php file is saved as one file and the HTML is placed within an existing page. You also need to make sure the "form" tag is correctly pointed to the PHP file.
 jamie  Fri Mar 16, 2007 2:11 am  
hi this is it sorted thanks for this wee scipt its funky!

How do i add more fields?
 Koki Mourao  Wed Mar 28, 2007 12:17 pm  
Hi,

I implemeted it and even got a Thank You text on contact.php. but nothing is landing on my inbox... what am I doing wrong?

Thank you
 mkeefe  Wed Mar 28, 2007 7:07 pm  
Make sure you have php set up to send mail on your server. The quickest way to check is to run the script by filling in the $_POST data for testing and then view it in browser. If you don't get any error messages then you are ok.
 Elliot  Mon May 14, 2007 10:03 pm  
Every time i click submit my computer trys to download the php file "contact.php" and does not send anything what is happening???
 mkeefe  Tue May 15, 2007 1:37 am  
That usually means you don't have PHP installed or you haven't updated Apache to look for PHP.
 Elliot  Tue May 15, 2007 7:48 am  
Im using dreamweaver and a php page on that does this still mean i need PHP and apache???
 mkeefe  Fri May 18, 2007 9:46 am  
Yes, you would still need PHP and apache or a similar web server technology.
 Brock  Sun Jun 10, 2007 4:59 am  
Thanks for all the time to answer questions. Above you mention a way to test the script in the browser.

How, exactly, would I run a PHP script locally, in my browser (Firefox) to test it?
 mkeefe  Sun Jun 10, 2007 10:59 pm  
There is a few ways to run PHP locally, the first is to install it by hand.. not always quick, but fun.

The next option is the Zend Core which has all of its pieces in one nice easy to use installer for both mac/pc.

Finally you can use PHPTriad and there is one other I know I am forgetting to mention.. maybe someone else knows.
 Ron  Tue Jul 31, 2007 7:13 pm  
Thanks for the great script! I am new to building websites and this was cool to find! Everything works great but is there a way to get the '$result =' to stay in the website instead of opening an untitled window with the Thank You message? I could create another page in my website with a thank you window but is it possible to link the submit button to another XHTML page? Any input would be greatly appreciated.
 Georgia  Tue Oct 16, 2007 5:47 pm  
Thank you thank you thank you. I really love your simple explanation and break-down. I spent hours trying to figure out how to make my form work on a client site. As a print based graphic designer this whole world of web is pretty daunting and your simple form really helped me out.
 justin  Tue Oct 30, 2007 7:42 am  
I copied and Pasted this script
i have never done php in my life

But i added some forms and changed there ID so that part should work

for the $server_name

Should i have some kind of server that will send it or should it send it if i put anything there?

And when i tested it
i got this

Thank you.
I will get back to you very soon.
"; } else { $result = "Sorry: An error occured, please try again later."; } } // Output a result Message print $result; ?>

After i pushed the submit and nothing is in my email

But if i need some kind of server to send the email
can you please email me
how to get it to send

justinpeters6@gmail.com

thank you.

Justin
 Michael Ross  Thu Nov 29, 2007 11:49 am  
I need a Php mailer
 Michael Ross  Thu Nov 29, 2007 11:51 am  
I need a php mailer.contact me via mich001_ross@yahoo.co.uk
 Nicanor  Wed Feb 6, 2008 4:37 am  
hi, how do i get a php mailer for to reach my clients outside of my domain?

how can give me a nowledge of php creation. i seem not to understand much on what is provided in the forum, please put it in line what first and what second and where to summit to. thanx
 mkeefe  Wed Feb 6, 2008 6:01 am  
@Nicanor - I am not sure what you mean. Are you asking how to access this PHP file from a remote location?
 Scott Freeland  Wed Feb 6, 2008 10:41 am  
love the code, works great, nothing better than when you can get something to work! Freekin sweet, thanks
 David  Wed Feb 6, 2008 10:42 am  
I don't get which parts go in my .php and which go in my contact.html, it is unclear
 mkeefe  Wed Feb 6, 2008 11:22 am  
@David - The first block of code is HTML. The last code block is the PHP. Hope that helps.
 David  Wed Feb 6, 2008 1:37 pm  
Thanks, I set it all up but I get "Sorry: An error occured, please try again later" when test sending. I'm using awardspace as my host, are they uncomputable with this PHP?
 mkeefe  Wed Feb 6, 2008 1:42 pm  
@David - Have you attempted to run the PHP directly in your browser? That will determine if PHP is enabled from your host.
 Sharyn  Mon Apr 28, 2008 9:09 pm  
Hi there, I am trying to implement this for a client site and while the email is sending, I am getting nothing in the body of the email other than the fields, and no actual details.
It tells me this;
Sender Name:
Sender E-Mail:
Date Sent: April 29, 2008
Message:

but as you can see, the information is missing!

 mkeefe  Tue Apr 29, 2008 4:42 am  
A potential cause for that is incorrect field names, or not properly filling them to begin with. I would start by checking your $_POST data variables.
 Sharon Ross  Thu May 22, 2008 8:33 am  
If I have the php referenced in a flash file, have it in the same root file, and try to implement and upload to godaddy...will this code work?

Thank you
 mkeefe  Thu May 22, 2008 8:34 am  
Godaddy should allow PHP, but you might want to check with your host to be sure.
 sharon ross  Thu May 22, 2008 8:40 am  
they do...but I'm kind of on a learning curve here and have used flash (pro 8) components (combobox & radio buttons). I'm a bit lost as to integrating flash, php, dreamweaver and godaddy. Right now I have the form up using just AS code and it is directed to the visitor's default email prgram, variables intact and they must send from there. Not very professional unfortunately.
 mkeefe  Thu May 22, 2008 8:49 am  
Basically you would create an SWF and a .php file. The PHP file as shown above is built, just change the email address.

The Flash is also written, you would just point to the .php file on your server:

Such as:
http://example.com/emailer.php

 Sharon Ross  Thu May 22, 2008 9:04 am  
Thank you so much for all of your help! I'll be at it again today...wish me luck!!

Have a great weekend!
 Jason  Wed Jun 11, 2008 10:25 am  
I'm going to try out this php mailer. I have a bunch of fields I need to add. Nothing "funky" should happen if I add some drop downs in my form should it? As long as I name them and add variables to the php everything should work fine yes?

Part 2 - Instead of posting a "success" message can I bounce them to another page on the site?

/* message */
$message = "
Sender Name: $namen
Sender E-Mail: $emailn
Sender Street: $address1
Sender Street2: $address2
Sender CityStateZip: $address3
Sender Make: $make
Sender Year: $year
Date Sent: $daten
Message:n----------------------------------------n$message n";

if(mail($to, $subject, $message, $headers))
{
$result = "http://www.mySite.com/emailSuccess.html";
}
else
{
$result = "Sorry: An error occured, please try again later.";
}
}

// Output a result Message
print $result;
?>

Is that correct what's above?
 mkeefe  Wed Jun 11, 2008 10:30 am  
@Jason, You can certainly add more fields as needed. For the loading of another page you would need to use the header() function.

header("Location: " . $result);

but make sure it is before all output, otherwise it will throw a "Headers already Sent" warning.
 Jason  Wed Jun 11, 2008 10:46 am  
So would i write it like this:

if(mail($to, $subject, $message, $headers))
{
$result = header("http://www.mySite.com/emailSuccess.html" .$result);
}
else
{
$result = "Sorry: An error occured, please try again later.";
}
}

// Output a result Message
print $result;
?>
 mkeefe  Wed Jun 11, 2008 10:51 am  
Not exactly, the "Location: " is part of command in PHP.

So its literally:

header("Location: " . $result); // result is the full url
 Jason  Wed Jun 11, 2008 10:53 am  
Ok I'm confused....so it's like this?

if(mail($to, $subject, $message, $headers))
{
$result = header("Location:http://www.mySite.com/emailSuccess.html" .$result);
}
else
{
$result = "Sorry: An error occured, please try again later.";
}
}

// Output a result Message
print $result;
?>
 mkeefe  Wed Jun 11, 2008 11:01 am  
Ok, let me create the block of code so you can understand it a little better.

$result = "http://www.mySite.com/emailSuccess.html";

if(mail($to, $subject, $message, $headers))
{
header("Location: " . $result);
}
else
{
print "Sorry: An error occured, please try again later.";
}

Hope that helps.
 Jason  Wed Jun 11, 2008 11:22 am  
I'm getting a parse error:
Parse error: parse error, unexpected $ in /home/virtual/site458/fst/var/www/html/stb/sales_contact.php on line 70

all that's on line 70 is "?>"

i have the code written like this:

$build_message = false;
if($action != "")
{
$build_message = true;
$message = trim($_POST['message']);
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$address1 = trim($_POST['address1']);
$address2 = trim($_POST['address2']);
$address3 = trim($_POST['address3']);
$make = trim($_POST['make']);
$year = trim($_POST['year']);
$time = time();
$date = date("F j, Y", time());
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/plain; charset=UTF-8rn";
$headers .= "From: $emailrn";
$headers .= "X-mailer: " . $server_name . " Serverrn";
}

if($build_message)
{
/* message */
$message = "
Sender Name: $namen
Sender E-Mail: $emailn
Date Sent: $daten
Message:n----------------------------------------n$message n";

$result = "http://www.site.com/emailSuccess.html";

if(mail($to, $subject, $message, $headers))
{
header("Location: " . $result);
}
else
{
print "Sorry: An error occured, please try again later.";
}

// Output a result Message
print $result;
?>

i pulled out the :
// Output a result Message
print $result;

and still got the same parse error.
 mkeefe  Wed Jun 11, 2008 11:33 am  
My mistake. There should be a closing } after the error string, such as:

print "Sorry: An error occured, please try again later.";
}
}
 tbright  Sun Jun 29, 2008 11:22 am  
Yesterday, after clicking the submit button it redirected me to a page saying "Thank you.
I will get back to you very soon.
"; } else { $result = "Sorry: An error occured, please try again later."; } } // Output a result Message print $result; ?>"

Today, although I have made no changes to anything, I am now getting a HTTP Error 405 - The HTTP verb used to access this page is not allowed.
Internet Information Services (IIS)!? I'm just not sure what I'm missing.


$to = "webmaster@californiawagelawyer.com" . ", " ;

$subject = "Comment From " . "californiawagelawyer";

$server_name = "californiawagelawyer";

if (!empty($_POST['send']) || !empty($_GET['send']))
{
$action = (!empty($_POST['send'])) ? $_POST['send'] : $_GET['send'];
}
else
{
$action = '';
}

$build_message = false;
if($action != "")
{
$build_message = true;
$message = trim($_POST['details']);
$name = trim($_POST['name']);
$number = trim($_POST['contact_number']);
$time = time();
$date = date("F j, Y", time());
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/plain; charset=UTF-8rn";
$headers .= "From: $emailrn";
$headers .= "X-mailer: " . $server_name . " Serverrn";
}

if($build_message)
{
$message = "
Sender Name: $namen
Sender E-Mail: $emailn
Date Sent: $daten
Message:n----------------------------------------n$message n";

if(mail($to, $subject, $message, $headers))
{
$result = "Thank you.
I will get back to you very soon.
";
}
else
{
$result = "Sorry: An error occured, please try again later.";
}
}

print $result;
?>

 mkeefe  Sun Jun 29, 2008 1:52 pm  
That looks like an IIS (Internet Information Server), not Apache. Therefore not Linux and quite possibly mail() is not enabled or configured. You may want to contact your hosting provider.
 Jake  Thu Jul 24, 2008 9:54 am  
I put it on and when I send one it goes in my Inbox but the Name, Email, and Comment fields are blank? It just says:

Sender Name:

Sender E-Mail:

Date Sent: July 24, 2008

Message:


---
But even though it tells me it sent, and it does, the message and name & email aren't there!
 mkeefe  Sun Jul 27, 2008 6:05 pm  
@Jake - Did you check to make sure your variables are properly defined?
 Jake  Wed Jul 30, 2008 2:44 pm  
Yeah! I set them all, I have the email at my email.. Name, etc. But it is just blank! :P Please help out.
 Nate  Mon Nov 10, 2008 1:59 pm  
I found this code in a book, and it didn't work because my provider wants it to be set to smtp, how do i add the smtp to the code for this one? I am using flash form to get all the variables, the only thing I am missing is the smtp code for it.

Thank you!

/*----------------------------------------------------------
Author : www.mkeefedesign.com | Matthew Keefe
Contact : matt@mkeefedesign.com
$Id: send_email.php ,v 1.0 Tue Apr 26, 2005 02:20 PM
------------------------------------------------------------
* CODING & DESIGN 2004 mkeefeDESIGN | ALL RIGHTS RESERVED
------------------------------------------------------------*/

$recipients = "youremail@yourdomain.com" . ",";
$subject = "The Message";

// The following three variables are gathered from Flash
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['msg'];
$phone = $_POST['phone'];


// Grab todays date
$date = date("F j, Y", time());

// This block is the actual message that is sent in the email
$email_info .= "Below is the visitors contact info and message.nn";
$email_info .= "Visitor's Info:n";
$email_info .= "-----------------------------------------n";
$email_info .= "Name: " . $name . "n";
$email_info .= "Email: " . $email . "n";
$email_info .= "Phone: " . $phone . "n";
$email_info .= "Date Sent: " . $date . "nn";
$email_info .= "Messagen";
$email_info .= "-----------------------------------------n";
$email_info .= "" . $message . "n";

$mailheaders = "From: " . $email . "n";
$mailheaders .= "Reply-To: " . $email . "nn";

if(mail($recipients, $subject, $email_info, $mailheaders)) {
// Print a success for Flash to know the email is being sent
print "&success=true";
}

?>
 mkeefe  Mon Nov 10, 2008 2:04 pm  
@Nate - SMTP is beyond the scope of this tutorial. I recommend something like the following to help you:

http://email.about.com/od/emailprogrammingtips/qt/et073006.htm

I may write up an in depth guide to SMTP at some point.
 Randy  Wed Mar 18, 2009 4:39 am  
Hi, This code all works perfectly on my testing server, but after I uploaded the site to the companies server, this email script doesn't work anymore, any one know why this would happen??
 mkeefe  Wed Mar 18, 2009 5:30 am  
@Randy - The most common reason is different mailing settings where standard PHP mail() is not enabled. Also make sure there aren't any errors in the PHP error_log.
 Jon Noeth  Tue Oct 20, 2009 8:31 am  
THANKS SO MUCH!!! THIS WAS SO HELPFUL!
 Tumble  Wed Oct 28, 2009 7:48 am  
Thanks mkeefe for this script, it was exactly what I was looking for!

For anyone interested: I used http://www.phpform.org/ to create a sleek looking form, modified the script's variables and had a working form in 10mins!
 Greg  Fri Nov 27, 2009 3:09 pm  
Does anyone know how to modify the $to part of the form so that it can send the form to both a consistent address plus the email address of the user that filled it out?

I am looking to use this form where a copy is sent to the person filling out the form.
 shoops  Wed Feb 10, 2010 12:00 pm  
HI

i created the form. and it works. as in like it does sends the info to my email. The only thing that i am battling with is Instead of posting a "success" message, I need it bounce them to another page on the site. I tried using your above suggested code

$result = "http://www.mySite.com/emailSuccess.html";

if(mail($to, $subject, $message, $headers))
{
header("Location: " . $result);
}
else
{
print "Sorry: An error occured, please try again later.";
}

But i get an "Headers already Sent" error message. What am i doing wrong?
 Jeremy  Mon Apr 12, 2010 7:05 am  
I've been playing around with this script quite a bit in the past couple days, and can't seem to get it to work. Whenever the submit button is pressed, I just get a 404 error. Both files are hosted in the same exact directory. Is this possibly caused by php not being enabled?
 mkeefe  Wed Apr 21, 2010 1:46 pm  
@Jeremy - Sounds like PHP is indeed NOT configured or installed.
 Jeff  Mon May 3, 2010 11:13 am  
How can i get this to work with radio boxes and check boxes because its not working with my form?
 mkeefe  Mon May 3, 2010 12:19 pm  
@Jeff - Radio Buttons and Checkboxes use an array system, so your code (in HTML) would look like this:


<input type="checkbox" name="my_rb[]" value="1" />
<input type="checkbox" name="my_rb[]" value="2" />
<input type="checkbox" name="my_rb[]" value="3" />


Then in the PHP you would reference them like:


print_r($_POST['my_rb']);


You could then use those values in your own code and load them into the email processor.

Hope that helps.

Matt
 Paul Marshall  Fri Jan 27, 2012 5:17 pm  
can the script be adjusted to include a subject field on a form inserted by the user that lands in the subject field of a standard email rather than the fixed subject in the php file. Rather like as if you were sending a standard email and input a subject.
 mkeefe  Fri Jan 27, 2012 5:32 pm  
@Paul Marshall Yes, just create another POST variable in the PHP and input entry in the HTML. Then instead of the static subject you'd do.

$subject = $_POST['subject'];

Hope that helps.
Add a comment
The ability to add new comments has been disabled in this archived version.

Loading
Main | Tutorials | Articles