HostGator.com » Support Portal

How to use sendmail with PHP

Here is the magical line of code which tells PHP to send an email through your mail server. Please remember we do not offer support to code this, nor do we promise to make your code work.

mail("receiving-email","subject","message-body","headers");

The best benefit of PHP code is that it is read on the server, not by your browser. This means that no one can see your email address or the PHP code used to send the email.


You may even copy and paste this working example. Create a file named email_form.php and paste this code inside and save. (If you use a different file name, you must change that file name as shown in bold in the code sample.)

Note: You will need to replace postmaster@example.com with your real email address. You can use any email address you want, even a third party email hosted somewhere else.

Note: You will also need to replace thank_you.html with the real page name where visitors are sent after they submit the form.

<?php
switch (@$_GET['do'])
 {

 case "send":

      $fname = $_POST['fname'];
      $lname = $_POST['lname'];
      $femail = $_POST['femail'];
      $f2email = $_POST['f2email'];
      $saddy = $_POST['saddy'];
      $scity = $_POST['scity'];
      $szip = $_POST['szip'];
      $fphone1 = $_POST['fphone1'];

      $mname = $_POST['mname'];
      $sapt = $_POST['sapt'];
      $sstate = $_POST['sstate'];
      $scountry = $_POST['scountry'];
      $fphone2 = $_POST['fphone2'];
      $fphone3 = $_POST['fphone3'];
      $fsendmail = $_POST['fsendmail'];
      $secretinfo = $_POST['info'];

    if (!preg_match("/\S+/",$fname))
    {
      unset($_GET['do']);
      $message = "First Name required. Please try again.";
      break;
    }
    if (!preg_match("/\S+/",$lname))
    {
      unset($_GET['do']);
      $message = "Last Name required. Please try again.";
      break;
    }
    if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$femail))
    {
      unset($_GET['do']);
      $message = "Primary Email Address is incorrect. Please try again.";
      break;
    }
    if ($f2email){
      if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$f2email))
      {
        unset($_GET['do']);
        $message = "Secondary Email Address is incorrect. Please try again.";
        break;
      }
    }
    if (!preg_match("/\S+/",$saddy))
    {
      unset($_GET['do']);
      $message = "Street Address required. Please try again.";
      break;
    }
    if (!preg_match("/\S+/",$scity))
    {
      unset($_GET['do']);
      $message = "City required. Please try again.";
      break;
    }
    if (!preg_match("/^[0-9A-Za-z -]+$/",$szip))
    {
      unset($_GET['do']);
      $message = "Zip/Post Code required. Please try again.";
      break;
    }
    if (!preg_match("/^[0-9 #\-\*\.\(\)]+$/",$fphone1))
    {
      unset($_GET['do']);
      $message = "Phone Number 1 required. No letters, please.";
      break;
    }
 
    if ($secretinfo == "")
    {
       $myemail = "postmaster@example.com";
       $emess = "First Name: ".$fname."\n";
       $emess.= "Middle Name: ".$mname."\n";
       $emess.= "Last Name: ".$lname."\n";
       $emess.= "Email 1: ".$femail."\n";
       $emess.= "Email 2: ".$f2email."\n";
       $emess.= "Street Address: ".$saddy."\nApt/Ste: ".$sapt."\n";
       $emess.= "City: ".$scity."\nState: ".$sstate."\nZip/Post Code:".$szip."\n";
       $emess.= "Country: ".$scountry."\n";
       $emess.= "Phone number 1: ".$fphone1."\n";
       $emess.= "Phone number 2: ".$fphone2."\n";
       $emess.= "Phone number 3: ".$fphone3."\n";
       $emess.= "Comments: ".$fsendmail;
       $ehead = "From: ".$femail."\r\n";
       $subj = "An Email from ".$fname." ".$mname." ".$lname."!";
       $mailsend=mail("$myemail","$subj","$emess","$ehead");
       $message = "Email was sent.";
    }
 
       unset($_GET['do']);
       header("Location: thank_you.html");
     break;
 
 default: break;
 }
?>


<html>
<body>
<form action="email_form.php?do=send" method="POST">
<p>* Required fields</p>
<?php
   if ($message) echo '<p style="color:red;">'.$message.'</p>';
?>
   <table border="0" width="500">
     <tr><td align="right">* First Name: </td>
         <td><input type="text" name="fname" size="30" value="<?php echo @$fname ?>"></td></tr>
     <tr><td align="right">Middle Name: </td>
         <td><input type="text" name="mname" size="30" value="<?php echo @$mname ?>"></td></tr>
     <tr><td align="right">* Last Name: </td>
         <td><input type="text" name="lname" size="30" value="<?php echo @$lname ?>"></td></tr>
   </table>
<p>
   <table border="0" width="500">
     <tr><td align="right">* Primary Email: </td>
         <td><input type="text" name="femail" size="30" value="<?php echo @$femail ?>"></td></tr>
     <tr><td align="right">Secondary Email: </td>
         <td><input type="text" name="f2email" size="30" value="<?php echo @$f2email ?>"></td></tr>
   </table>
<p>
   <table border="0" width="600">
     <tr><td align="right">* Street Address: </td>
         <td><input type="text" name="saddy" size="40" value="<?php echo @$saddy ?>"></td></tr>
     <tr><td align="right">Apartment/Suite Number: </td>
         <td><input type="text" name="sapt" size="10" value="<?php echo @$sapt ?>"></td></tr>
     <tr><td align="right">* City: </td>
         <td><input type="text" name="scity" size="30" value="<?php echo @$scity ?>"></td></tr>
         <td align="right">State: </td>
         <td><input type="text" name="sstate" size="10" value="<?php echo @$sstate ?>"></td></tr>
     <tr><td align="right">* Zip/Post Code: </td>
         <td><input type="text" name="szip" size="10" value="<?php echo @$szip ?>"></td></tr>
     <tr><td align="right">Country: </td>
         <td><input type="text" name="scountry" size="30" value="<?php echo @$scountry ?>"></td></tr>
   </table>
<p>
   <table border="0" width="500">
     <tr><td align="right">* Phone Number 1: </td>
         <td><input type="text" name="fphone1" size="20" value="<?php echo @$fphone1 ?>"></td></tr>
     <tr><td align="right">Phone Number 2: </td>
         <td><input type="text" name="fphone2" size="20" value="<?php echo @$fphone2 ?>"></td></tr>
     <tr><td align="right">Phone Number 3: </td>
         <td><input type="text" name="fphone3" size="20" value="<?php echo @$fphone3 ?>"> <input style="display:none;" name="info" type="text" value=""> </td></tr>
   </table>
<p>
   <table border="0" width="500"><tr><td>
     Comments:<br />
     <TEXTAREA name="fsendmail" ROWS="6" COLS="60"><?php if($fsendmail) echo $fsendmail; ?></TEXTAREA>
     </td></tr>
     <tr><td align="right"><input type="submit" value="Send Now">
     </td></tr>
   </table>
   </form>
</body>
</html>

Article Comments

Charles
Is it possible to have a simple own php mail script form?
I consider this script too extensive.. It asks telephone number, address and all that. I think most mail forms just have name subject email and message... Do you have a script less extensive? Can I use one of my own?

HostGator
You may use our example and simply remove the lines you do not want.

You may also write or upload your own PHP code.

I am working on an official PHP email form we can offer to all customers.

David
I get the error below after I click submit. The email is sent but it seems to have a problem with "header("Location: thank_you.html");" Btw, I have a file named the same. The page reloads with the error message at the top.

Warning: Cannot modify header information - headers already sent by (output started at /home/******/public_html/contact.php:1) in /home/******/public_html/contact.php on line 34

- as noted above, line 34 is:

header("Location: thank_you.html");

Thanks in advance for your help

HostGator
The problem is that you have output HTML code before the PHP code. Please make sure that there is no additional code preceding the first "<?php" line.

Read more at http://support.hostgator.com/articles/getting-started/general-help/php-cannot-modify-header-information

If you did not paste extra code, it is possible you have enabled a feature like auto_prepend_file.

Catharine Hendricks
I just want to thank you for this script -- it's EXACTLY what I've been looking for and I've already implemented it in my project.

If you do finish that official PHP email form, I'd love to hear about it.

In any case -- thanks again!

Catharine Hendricks
(satisfied customer)

Lynard
how can I put the email_form.php the a certain webpage. I used sitebuilder and cannot see my whole webpage file.

HostGator
Try the article entitled "How do I insert custom code into my site design?"

Claude
I have about four hundred subscribers of my newsletter. Is there a limit to the number of BCC email addresses that can be included in an outgoing email?

Thank you.

HostGator
If you are on a shared server, then yes, you are limited to 500 outgoing email addresses per hour. (This is a separate limit of 500 for every domain hosted with HostGator).

Even if you have much less than 500 recipients, you must still throttle every email list, so this is risky if you are not using a mailing list program which can throttle. I recommend installing phpList and using that.

Maxi
After many years with you this is another example of why "I LOVE YOU MAN!"

Dana
Where in the my hosted space should the "email_form.php" file be placed? Can it be laced in a non public area? My concern is the email address could be read by spam crawlers if it's public.

HostGator
That is the beauty of this PHP form. Your email address cannot be seen by anyone.

gabriel landaeta
Thanks guys for your great work.
in this time i want to ask there is any way i can modify the php sendmail parameter that makes always appears in my emails the following line
mailed-by xlr.websitewelcome.com

HostGator
Sure, just add that value to one of the 4 variables in the mail() function.

$myemail, $subj, $emess, $ehead

morningmouse
When I create the form using dreamweaver, what should I include under action? Is it Action=http:/mydomain/email.php or email_form.php?

HostGator
action="email_form.php?do=send"

That is assuming you named the file 'email_form.php'. If you named your file 'email.php', then the correct answer would be...

action="email.php?do=send"

Zafer
This method sends email to @yahoo.com, or hotmail.com but doesnot send emails to corporate domains. like @example.com

HostGator
This form works for sending to ALL emails, even corporate domains.

I think you are confused because example.com is reserved as an example and is not possible to register. Please visit http://example.com for more details.

Tonino
Is there anyway to add a CC or BCC using the examples above?

HostGator
Sure, very easy to do if you know the addresses or variables you want to use.

$ehead = "From: $femail \r\n";
$ehead .= "Reply-To: $myemail \r\n" .
$ehead .= "Cc: sitearchive@example.com \r\n";
$ehead .= "Bcc: me@gmail.com \r\n";

Donald
Thanks for the script. This is actually my first attempt at working with PHP. The script works fine, but how do you prevent what's in the "value" from showing in the actual HTML form?

HostGator
The values don't show in the form unless you submit it and it comes back with an error. This prevents the visitor from needing to start all over.

If you are seeing value="<?php echo @$fname ?>" in the browser source code, then you may have named the file email_form.html (something other than .php).

Keith
In your script, certain fields are required. But when one or more of those required fields are left blank, you don't see, for example, "Last Name required. Please try again". What you get is a blank screen and you have to hit your back button to return to the form. Thanks for your help.

HostGator
The form sure does produce specific error messages. Even when it fails, you should see the form again.

I suspect you have the wrong file name in your form tags. If the action="wrong-name.php", then it will load that wrong-name.php page as if you clicked a link to it.

EXAMPLE
If you named the file emailform.php, then you must update the code from
<form action="email_form.php?do=send" method="POST">
to
<form action="emailform.php?do=send" method="POST">

HostGator
UPDATE: This form no longer depends on register_globals On.

You can set register_globals Off and it will work the same.

ronald
hi, I created the file, email_form.php, copied the code and uploaded it to public_html, now I'm working with dreamweaver, so not to sure of where to put the (mail("receiving-email","subject","message-body","headers"); line, I copied it in the action field in the properties bar, if that's where is suppose to go I'm getting the fallowing error:

( The requested URL /mail("receiving-email","subject","message-body","headers"); was not found on this server.

Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.


could you please tell me what I'm doing wrong

thanks in advance

HostGator
Don't use the mail("receiving-email","subject","message-body","headers"); part. That was merely an example of the code structure.

If you copied the sample form, saved it as email_form.php, and uploaded it to your document root folder, then all that is left is to put a link to it from your home page.

Here is a sample of the HTML code:

<a href="email_form.php">Click here to contact me via email.</a>

Webmistress
What a great thread! Thanks HostGator and everyone!
The Bcc: was especially helpful!

Tom
Hello.

1) I copied this php form in my html webpage.
2) I can send email from foorm and all is doing great...
3) BUT... as soon as i have entered value and than click send i got NEW clean webpage with just form ( email_form.php)
4) I want that if something went wrong - i stayed in the same page.. i understand VERY good that action is set to open email_form.php but i have inserted this code in my html web..
THIS IS THE SAME what Keith comented here... I have the same thing.

So, what to do - maybe i can add additional code that if something goes wrong it stays in my contact.html page and not opening email_form.php ...

I hope You can help!

Thanks !

Best,
Tom

HostGator
To accomplish your goal, you need to be very comfortable with HTML code.

1. Change the name of your contact page to contact.php .

2. Paste the PHP code in my sample at the very top of your contact.php page (before all the other HTML code, and do not let there be even one blank space before my PHP code).

3. Paste the HTML for my contact form into the middle of your existing HTML code, where ever you want it to appear. Omit my "<html><body>" and "</body></html>". (WARNING: If you insert my HTML in the wrong area of your HTML code, you may break your site.)

4. Finally, change the ACTION value to contact.php, like so...
<form action="contact.php?do=send" method="POST">

This will achieve your goal, but should only be attempted by someone who understands the consequences of doing this wrong. HostGator will NOT be able to help you with these custom instructions nor fix your coding mistakes.

Pete
I am trying to use this script that came programmed with my flash website template and nothing seems to come through - i have it in the same directory as the flash files - in flash it the PHP is linked to ActionScript 2.0
Any way to test it? Any thing look off? Thanks for your advice:

<?php
//Type the receiever's e-mail address
$emailAddress = "info@mydomain.com";
//Type your Site Name
$siteName = "My Domain";

$contact_name = $_POST['name'];
$contact_email = $_POST['email'];
$contact_subject = $_POST['subject'];
$contact_message = $_POST['message'];

if( $contact_name == true ) {
$sender = $contact_email;
$receiver = $emailAddress;
$client_ip = $_SERVER['REMOTE_ADDR'];

$email_body = "The Name Of The Sender: $contact_name \nEmail: $sender \n\nSubject: $contact_subject
\n\nMessage: \n\n$contact_message \n\nIP ADDRESS: $client_ip \n\n$siteName";

$emailAutoReply = "Hi $contact_name, \n\nWe have just received your E-Mail. We will get
in touch in a few days. Thank you! \n\n$siteName ";

$extra = "From: $sender\r\n" . "Reply-To: $sender \r\n" . "X-Mailer: PHP/" . phpversion();
$autoReply = "From: $receiver\r\n" . "Reply-To: $receiver \r\n" . "X-Mailer: PHP/" . phpversion();

mail( $sender, "Auto Reply: $contact_subject", $emailAutoReply, $autoReply );

if( mail( $receiver, "New E-Mail - $contact_subject", $email_body, $extra ) ) {
echo "success=yes";
} else {
echo "success=no";
}
}
?>

HostGator
Pete, your code definitely does not work, though I am not sure why. All I can do is offer you my working sample.

Daniel
Hi, I have created this email_form.php and uploaded it to my server and tested it out and it does not seem to work. My recently switched to hostgator from another host and my other contact forms also do not work. i tried a simple mailtest.php and it does not work either. I have a reseller account. Any ideas?

<?php
mail('you@yourmail.com','Test mail','The mail function is working!');
echo 'Mail sent!';
?>

HostGator
The code works fine. Possibly you have an incorrect email address or an incompatible PHP setting on your account.

Please, contact support@hostgator.com if you still cannot get the code to work.

John
very nice code, great place for me to start learning about php
tried the html only code couldn't get the results I wanted
this works great, easy to follow, simple to edit
I split the php and the html and replaced nine forms with just one
working perfectly on the day my previous host warned me I'd used up all of my measly 25 forms/month allowance
yet another good reason for moving my site to hostgator. Thanks John B

Jon
Hello, Will this form prevent spam injections? How secure will this be on its own? I have heard of a way of tricking spam bots by putting an invisible field on the form that humans can't see, but bots would fill out and if they did it would not send the e-mail. Could this script be tailored in a way that checks a certain invisible field and if it is not blank reject the e-mail?

HostGator
Great suggestion. I have added more code to achieve this.

The input named "info" will not be seen by humans, but will be seen by robots. If the robot puts anything in the info field, then the thank you page is displayed, but no email is sent.

Irispat.com
Guys, thank you so much. This is just the script I was looking for.

Sergio
Great script, I was able to implement it into a site fairly easily. Except one thing, I can't get the form to validate! I don't see what I am doing wrong in the code and if the form is submitted with a required field blank it just goes white. Odd.

Sergio
Nevermind, figured it out. Thanks for nothing!

Just kidding, great script. Worked like a charm.

Susan
So...is there no way to use this form but keep the php in an external file? I have to add this form to every page of a website, and that will change all the URLs from .htm to .php. On this particular website, I don't want to do all those redirects right now, for SEO reasons.

In any case, thanks so much for the form. It's easy and works great.

Adept Designs
Thanks! Made a few edits so it would fit my desired functionality, but I needed the core of the code in order to accomplish this.

You are the BEST Host Gator!

Adolph
The form says that email was sent bu i never receive it? here is the code:

<?php
switch (@$_GET['do'])
{

case "send":

$fname = $_POST['fname'];
$lname = $_POST['lname'];
$femail = $_POST['femail'];
$f2email = $_POST['f2email'];
$saddy = $_POST['saddy'];
$scity = $_POST['scity'];
$szip = $_POST['szip'];
$fphone1 = $_POST['fphone1'];

$mname = $_POST['mname'];
$sapt = $_POST['sapt'];
$sstate = $_POST['sstate'];
$scountry = $_POST['scountry'];
$fphone2 = $_POST['fphone2'];
$fphone3 = $_POST['fphone3'];
$fsendmail = $_POST['fsendmail'];
$secretinfo = $_POST['info'];

if (!preg_match("/\S+/",$fname))
{
unset($_GET['do']);
$message = "First Name required. Please try again.";
break;
}
if (!preg_match("/\S+/",$lname))
{
unset($_GET['do']);
$message = "Last Name required. Please try again.";
break;
}
if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$femail))
{
unset($_GET['do']);
$message = "Primary Email Address is incorrect. Please try again.";
break;
}
if ($f2email){
if (!preg_match("/^\S+@[A-Za-z0-9_.-]+\.[A-Za-z]{2,6}$/",$f2email))
{
unset($_GET['do']);
$message = "Secondary Email Address is incorrect. Please try again.";
break;
}
}
if (!preg_match("/\S+/",$saddy))
{
unset($_GET['do']);
$message = "Street Address required. Please try again.";
break;
}
if (!preg_match("/\S+/",$scity))
{
unset($_GET['do']);
$message = "City required. Please try again.";
break;
}
if (!preg_match("/^[0-9A-Za-z -]+$/",$szip))
{
unset($_GET['do']);
$message = "Zip/Post Code required. Please try again.";
break;
}
if (!preg_match("/^[0-9 #\-\*\.\(\)]+$/",$fphone1))
{
unset($_GET['do']);
$message = "Phone Number 1 required. No letters, please.";
break;
}

if ($secretinfo == "")
{
$myemail = "adolphkahn@gmail.com";
$emess = "First Name: ".$fname."\n";
$emess.= "Middle Name: ".$mname."\n";
$emess.= "Last Name: ".$lname."\n";
$emess.= "Email 1: ".$femail."\n";
$emess.= "Email 2: ".$f2email."\n";
$emess.= "Street Address: ".$saddy."\nApt/Ste: ".$sapt."\n";
$emess.= "City: ".$scity."\nState: ".$sstate."\nZip/Post Code:".$szip."\n";
$emess.= "Country: ".$scountry."\n";
$emess.= "Phone number 1: ".$fphone1."\n";
$emess.= "Phone number 2: ".$fphone2."\n";
$emess.= "Phone number 3: ".$fphone3."\n";
$emess.= "Comments: ".$fsendmail;
$ehead = "From: ".$femail."\r\n";
$subj = "An Email from ".$fname." ".$mname." ".$lname."!";
$mailsend=mail("$myemail","$subj","$emess","$ehead");
$message = "Email was sent.";
}

unset($_GET['do']);
header;
break;

default: break;
}
?>



<form action="testform.php?do=send" method="POST">
<p>* Required fields</p>
<?php
if ($message) echo '<p style="color:red;">'.$message.'</p>';
?>
<table border="0" width="500">
<tr><td align="right">* First Name: </td>
<td><input type="text" name="fname" size="30" value="<?php echo @$fname ?>"></td></tr>
<tr><td align="right">Middle Name: </td>
<td><input type="text" name="mname" size="30" value="<?php echo @$mname ?>"></td></tr>
<tr><td align="right">* Last Name: </td>
<td><input type="text" name="lname" size="30" value="<?php echo @$lname ?>"></td></tr>
</table>
<p>
<table border="0" width="500">
<tr><td align="right">* Primary Email: </td>
<td><input type="text" name="femail" size="30" value="<?php echo @$femail ?>"></td></tr>
<tr><td align="right">Secondary Email: </td>
<td><input type="text" name="f2email" size="30" value="<?php echo @$f2email ?>"></td></tr>
</table>
<p>
<table border="0" width="600">
<tr><td align="right">* Street Address: </td>
<td><input type="text" name="saddy" size="40" value="<?php echo @$saddy ?>"></td></tr>
<tr><td align="right">Apartment/Suite Number: </td>
<td><input type="text" name="sapt" size="10" value="<?php echo @$sapt ?>"></td></tr>
<tr><td align="right">* City: </td>
<td><input type="text" name="scity" size="30" value="<?php echo @$scity ?>"></td></tr>
<td align="right">State: </td>
<td><input type="text" name="sstate" size="10" value="<?php echo @$sstate ?>"></td></tr>
<tr><td align="right">* Zip/Post Code: </td>
<td><input type="text" name="szip" size="10" value="<?php echo @$szip ?>"></td></tr>
<tr><td align="right">Country: </td>
<td><input type="text" name="scountry" size="30" value="<?php echo @$scountry ?>"></td></tr>
</table>
<p>
<table border="0" width="500">
<tr><td align="right">* Phone Number 1: </td>
<td><input type="text" name="fphone1" size="20" value="<?php echo @$fphone1 ?>"></td></tr>
<tr><td align="right">Phone Number 2: </td>
<td><input type="text" name="fphone2" size="20" value="<?php echo @$fphon2 ?>"></td></tr>
</table>
<p>
<table border="0" width="500"><tr><td>
Comments:<br />
<TEXTAREA name="fsendmail" ROWS="6" COLS="60"><?php if($fsendmail) echo $fsendmail; ?></TEXTAREA>
</td></tr>
<tr><td align="center"><input type="submit" value="Submit">
</td></tr>
</table>
</form>

HostGator
Thank you for your comments. Just a quick reminder that the comments on this page are not monitored by technical support staff, and that for support issues, it is best to contact us by live chat, phone or email so we can assist you right away.

Although comments are not monitored by technical support staff, they are moderated and read by technical writers. Comments will need to be approved by a moderator before appearing.

Our technical writers do read the comments periodically for the purposes of updating the articles, and do appreciate your feedback, suggestions and corrections to the articles themselves, as well as any suggestions or tips for readers of this article. However, support questions posted here are not guaranteed to be replied to in a timely manner or at all. For support issues, it is best to contact our support staff instead by live chat, email or phone.



Your comments help us keep the knowledge base updated. This is not a medium for support. If you have questions or need help, please contact us via email, phone or live chat for fast assistance.

Post Comment