HTML/PHP mail Form Tutorial

Well a lot of people keep asking about PHP mail forms. I don’t have Flash on this computer, so I’m just going to have to make everyone stick with a regular HTML form. I will give the code and then explain that code…Here is how I do it:



<?
//------------------------------------------------
// File: 'phpmail.php'
// Func: using mail();
//------------------------------------------------

$Subject = "Test E-mail";                         
$toEmail = "[email protected]";       

if($submit)
{
mail($fromEmail, $Subject, $nMessage."
From: ".$fromName."<".$fromEmail.">");
}
?>

<html>
<head>
<title>Mail Tutorial</title>
</head>
<body bgcolor="#FFFFFF">
<form method="post" action="<? echo($PHP_SELF) ?>">
Your E-mail: 

<input type="text" name="fromEmail" size="25"> <br>

Your Name: <input type="text" name="fromName" size="25"> <br>

Your Message: <br>

<textarea cols="50" rows="5" name="nMessage">Your Message Here...</text> <br>

<input type="submit" value="Submit">

</body>
</head>

ok, now to break apart the code… We’ll start with the HTML code. Everyone here should know this stuff, but if not, then here is a quick refresher…

<form method="post" action="<? echo($PHP_SELF) ?>">

**This piece defines the form’s action and method. Method is either “post” or “get”. The action is the path to the PHP file you are using. In this case, since we are using the same file, you use “echo($PHP_SELF)” to echo this page’s name. **

<input type="text" name="fromEmail" size="25">

Simple input field with the variable name “fromEmail”.

<input type="text" name="fromName" size="25"> 

Same thing. Simple input field with variable name “fromName”.

<textarea cols="50" rows="5" name="nMessage">Your Message Here...</text>

Textbox area with variable name "nMessage"

<input type="submit" value="Submit">

Creates the submit button

For more on HTML check out the links in this thread: Click Here!

[SIZE=3]Ok, now the PHP part of the code:[/SIZE]

$Subject = "Test E-mail";
$toEmail = "[email protected]";

These are variables for your e-mails subject and your target recipient’s e-mail. This is generally where you put your e-mail address if you are the one that is going to be recieving the e-mail

if(submit)
{
mail($fromEmail, $Subject, $nMessage."
From: ".$fromName."<".$fromEmail.">");
}

**This is an if statement that checks to see if the submit button has been pressed. If yes, then it executes the script inside the brackets.
The mail() function on the inside is what sends the e-mail to you. **

The mail function works like this:
mail ( string to, string subject, string message)

Thats pretty self explanitory… To, Subject, and Message…

Thats it. Any questions?

Oh yeah, make sure that the file has a .php extension. you can name it whatever you like (ie. “emailform.php”), but it must have a .php extension.

Quick thing:

mail() returns a boolean value (ie: true or false). So you can check to see if you did the code right…

do this:


if(submit)
{
      $resultMail = mail($toEmail, $Subject, $nMessage);
      if($resultMail)
      {
            print "Your e-mail has been sent.";
      }
      else
      {
            print "Your e-mail has not been sent.";
      }
}

that second if statement checks to see if the mail() script when thru correctly and if not then it prints out “Your e-mail has not been sent.” You can use this to help debug your code…

Well written tutorial. I understood it pretty well, even without having used php before.

that´s freaking good tute jubba :A+:

thanks a lot for that =)

Thanks guys, I appreciate it. If anything is unclear at all, then let me know because I am trying to make this is clear as possible so I dont confuse anyone. Here is a link to the script in action:

http://www.livetoskateboard.com/test/mail.php

That script will send an e-mail to the address that is placed in the “Your E-mail” text box.

For more on mail() check out the PHP manual, http://www.php.net

works like a charm.

well done jubba! we really needed a tute like that =)

Guigo: Thanks. I’m working on one using Flash, but I don’t have Flash on this computer so I need to wait a couple more days.

Another thing about this script (as you can see I’m not a mail() expert, truthfully the first time I ever used it was to do this tutorial, but now, me being the loser that I am, I am having fun with it), you know how in Outlook express, or many other mail clients you have those “From, bcc, cc, etc” headers? well the first script I gave you would not say who the e-mail was from. For me it would say “nobody” So to fix that, PHP includes additional headers that can be added. Here is how I add my “From” field and I also added a “BCC” field that sends an e-mail to another one of my accounts, don’t worry… once I was finished testing I removed the BCC field. :slight_smile:

Anyway… here is the modified code:


<?
$Subject = "Test E-mail";
$headers = "From: $fromName <$fromName@$SERVER_NAME> 
";
$headers .= "bcc: [email]je****[email protected][/email] 
";

if(submit == TRUE)
{
    mail($toEmail, $Subject, $nMessage, $headers);
}
?>

Self-explanitory right? no? Ok, well here is the explanation of it. I won’t touch $Subject, because we know what that is…So here is an explanation of $headers


$headers = "From: $fromName <$fromName@$SERVER_NAME> 
";
$headers .= "bcc: [email]je****[email protected][/email] 
";

the first $headers defines the “From:” field. the "
" tells PHP that there is supposed to be a line break (much like < br > in HTML). The second header adds the “bbc” value to the first, so if we were to print the variable $headers like this:


print $headers;

our output would be:

From: name< [email protected] > bcc: je****[email protected]

the “.=” adds strings together.

Ok anyway, Now that our strings are together, we have to place them in the code.


mail($toEmail, $Subject, $nMessage, $headers);

This will fill out the From: header and it wills end a blind copy to my server at school :slight_smile: Any questions?

Oh one quick thing, the PHP manual has a great post about using the headers that might help everyone:

Originally posted by Cookieme at http://www.php.net
**$headers .= "From: Name<[email protected]>
";
$headers .= "X-Sender: <[email protected]>
";
$headers .= "X-Mailer: PHP
"; //mailer
$headers .= "X-Priority: 3
"; //1 UrgentMessage, 3 Normal
$headers .= "Return-Path: <[email protected]>
";
//Uncomment this to send html format
//$headers .= "Content-Type: text/html; charset=iso-8859-1
";
//$headers .= "cc: [email protected]
"; // CC to
//$headers .= “bcc: [email protected]”; // separete multiple with commas **

a link to that is: PHP: mail - Manual just scroll down to get to that post. :slight_smile:

Cheers guys and girls,
Jubs :ninja:

nice jubba :wink:

One thing to note is register globals is off by default in PHP4. This means get or post variables arent directly accessible as variables within the email php. For post variables you can use


$_POST["variableName"];

to get that value. etc.

Yes, I forgot to mention that, however, I don’t think you need to do that if the PHP is contained on the same page as the form tho? or is that wrong?

even though its the same page… as form values, their transition into the php variable world is through that post header and wont be seen with register globals off :slight_smile:

Then my host must have them turned on on their server. That explains why its working without the $_POST I know about it, I tell everyone to do it all the time when they say that their form isn’t working. That is something that everyone leaves out of the tutorials, I can’t believe I forgot to put them in too… **** I’m stupid. Thanks for catching it…

excellent post Jubba. thanks for taking the time. I know a few
people who I’ll be forwarding here right now to learn, instead of
me teaching them. :beam:

/unflux
:goatee:

yeah, Jubba, I think its fairly standard for php hosts to have it on as not to break old PHP 3 pages using the variables in that manner. In most cases, your code will work absolutely fine :slight_smile: I find it a pain to use $_POST or $_GET etc, but its safer and more secure and actually does help you tell where the variable came from when dealing with the code :wink: More typing though

can anyne help me with this

i have no idea what your talking about

do i need a .php file then the HTML in my “body” tags or what

you need a file called “something.php” and then just place that code into that file. Change what you need changed and you should be able to figure out how to tweak it. Read thru, it explains everything…

cool, thnx man!!!

Jubba -
I loved the tut. As a matter of fact (even though you called yourself a loser - I think I won) I’ve made mailers in HTML, Flash, a guestbook, counters, and IP readers. I like PHP (I’m kindof a dork…you know?). Anyhow; the HTML mailer from the tut here sends two emails to me. One with everything I had put it, and one preceeding it that only says this:
From: <>
Any ideas why it’s doing this? If I hit the send button twice, it would preceed it, right? I’m pretty sure I’m not anyhow. Thank you!

*Originally posted by Freddythunder *
**…the HTML mailer from the tut here sends two emails to me. One with everything I had put it, and one preceeding it that only says this:
From: <>
**

This is happening to me also. Anyone know why this could be? Thanks for any help.

mail($fromEmail, $Subject, $nMessage."
From: ".$fromName."<".$fromEmail.">");

I think that instead of saying $fromEmail that should say $toEmail

Also, here’s another thing: at this part

if(submit)

That - at least for me - is evaluating to true whenever I simply load the page. Everytime I open the page, it sends an email to me. Is there a way to fix this? I’m going to put another if statement in there just checking if the email address is empty, but that’s only a patch.

Maybe that’s why you’re getting 2 emails?

it should be


if($submit)

typo in my script.

not sure about the two e-mails thing tho. It happens to me sometimes too, but not all the time. I’ll give it a look and see if I can figure it out…