go top

MEGA Sale

  • Colection of 65 PHP scripts for $4.29 each

Get 65 PHP scripts in a bundle for $4.29 each!

View Offer

Make contact form and send email in PHP

Tuesday, 6th December, 2011  /  PHP Tutorials  /  465 Comments
Having a contact form on your web site is vital when you need to know what your site visitors think about your web site. We will first create a simple contact form with 3 fields - Email address, Name, Comments. I will use a table to align the 3 fields and the Send button. Create a new file and paste the code below in it. Save it as test.php and upload it to your web server. Now, you have a web page (http://www.yourdomain.com/test.php) with a simple contact form on it.

<form action="test.php" method="post"> 
<table width="400" border="0" cellspacing="2" cellpadding="0">
<tr>
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
</tr>
<tr>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
</tr>
<tr>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
</tr>
<tr>
<td class="bodytext"> </td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form>


Then we will need the actual PHP code which will send the email when the above form is submitted. We will need to define the email that the message should be sent to ($ToEmail) and also the subject for the message that will be sent ($EmailSubject). Change youremail@site.com to your email address where the message should be sent and also add an appropriate subject for you message. The $mailheader variable is used to define the email message header. We set the From, Reply-To and Content-type fields for the message. There are some more fields that can be used but for this example we will only use these 3. Depending on your server configuration you may need to have the From and Reply-to fields be a valid email address from your server.If you have a domain name mysite.com, then you should use a valid email address such as contact@mysite.com. In this example I am sending the email using the actual email address that is submitted via the form on site. Next all the data submitted via the web form is taken from the $_POST variable and saved in the $MESSAGE_BODY variable. Using the nl2br function you will make all the new lines in your comments box appear as new lines in your email message too. Having all the needed data for our email message we will use the mail() function which will send that email for us.

<?php 
$ToEmail = 'youremail@site.com';
$EmailSubject = 'Site contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br />";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br />";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br />";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>


All we have to do now is to combine the web form and email sending code into a single page. We will use an IF statement to check if the form has been submitted and if so it will send that email and will show a "Your message was sent" message on the screen instead of the web form.

<?php 
if ($_POST["email"]<>'') {
$ToEmail = 'youremail@site.com';
$EmailSubject = 'Site contact form';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: ".$_POST["email"]."\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
$MESSAGE_BODY = "Name: ".$_POST["name"]."<br />";
$MESSAGE_BODY .= "Email: ".$_POST["email"]."<br />";
$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"])."<br />";
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure");
?>
Your message was sent
<?php
} else {
?>
<form action="test.php" method="post">
<table width="400" border="0" cellspacing="2" cellpadding="0">
<tr>
<td width="29%" class="bodytext">Your name:</td>
<td width="71%"><input name="name" type="text" id="name" size="32"></td>
</tr>
<tr>
<td class="bodytext">Email address:</td>
<td><input name="email" type="text" id="email" size="32"></td>
</tr>
<tr>
<td class="bodytext">Comment:</td>
<td><textarea name="comment" cols="45" rows="6" id="comment" class="bodytext"></textarea></td>
</tr>
<tr>
<td class="bodytext"> </td>
<td align="left" valign="top"><input type="submit" name="Submit" value="Send"></td>
</tr>
</table>
</form>
<?php
};
?>


You can also try out our FREE Sliding Contact Form.
Share on:

465 Comments to "Make contact form and send email in PHP"

Nextcommcorporation.com

Nextcommcorporation.com / January 16, 2024 at 12:00 pm

Nice

Nextcomm Corporation

Nextcomm Corporation / January 16, 2024 at 11:54 am

Very Nice!

NAEWTRER336944NERTHRTYHR

NAEWTRER336944NERTHRTYHR / January 6, 2024 at 20:54 pm

MERTYHR336944MAYTRYR

Nextcomm Corporation

Nextcomm Corporation / December 27, 2023 at 14:56 pm

Very Nice!

Maik Taormina

Maik Taormina / November 21, 2023 at 15:37 pm

Are you tired of the daily hustle and bustle, yearning for a moment of tranquility and relaxation? Look no further – we have something extraordinary in store for you!

Introducing MassageSolutions, your go-to haven for all things soothing and rejuvenating. We understand the importance of self-care, and that's why we've curated a collection of the finest electric massagers for every part of your body:

https://tinyurl.com/ymuw9jbj

Revitalize Your Feet: Step into a world of comfort with our handpicked foot massagers. Explore the reviews and find the perfect one to treat your tired soles.

Soothe Your Aching Back: Say goodbye to back pain! Explore our comprehensive back massager reviews and discover the key to a pain-free, relaxed spine.

️ Unwind Your Neck and Shoulders: Pressure in your neck and shoulders? We've got the solution! Explore our neck massager reviews to find the ideal device to melt away stress.

But that's not all – we've gone the extra mile to bring you the most popular and effective massagers in each category. Our reviews are detailed, honest, and designed to guide you to the perfect match for your relaxation needs.

Don't miss out on the chance to treat yourself or find the perfect gift for a loved one:

Click this link: https://tinyurl.com/ymuw9jbj

Premium Guest Posting Services

Premium Guest Posting Services / November 19, 2023 at 23:41 pm

Are you ready to skyrocket your digital presence and transform your business? Look no further! Our Premium Guest Posting Services are your gateway to a digital adventure that will take your brand into a powerhouse.

**Explore the Possibilities**: https://marketbeast.site

Here's why our service will leave you completely satisfied:

- **High-Grade Backlinks:** Access a staggering 30,611+ websites, offering premium backlinks that can elevate your website's search engine placement. These aren't just links; they're powerful endorsements from reputable sites with credible traffic and credibility.
- **Satisfaction Guarantee:** We are so confident in our service that we offer a unique satisfaction guarantee. You only pay when you are thoroughly content with the results. Your happiness is our top priority, and we're here to deliver our promises.
- **Drive More Traffic, Leads, and Sales:** Placing your content on strategic websites is the golden ticket to reaching your desired clientele, attracting loyal customers, and catapulting your sales. It's a surefire way to make your business prosper.
- **Affordable Marketing Solution:** Guest blogging is not only incredibly powerful but also cost-effective. It's a cost-efficient alternative to traditional paid advertising methods. Save money while unleashing remarkable outcomes.
- **Conquer the Search Engine Rankings:** Watch your website soar on Google as you secure premium backlinks from reputable websites. Witness your website climb the search engine rankings and gain the recognition you've always dreamed of.

Don't miss out on this fantastic chance to revolutionize your online presence and enjoy all the advantages that come with it. Our Premium Guest Blogging Solutions will make your business shine, and the best part is, it starts at just $3.99! Take the first step towards your online triumph today!

To get started or learn more, simply click here: Boost Your Presence. Your venture to online greatness begins now.

**Click here to Ignite Your Presence:** https://marketbeast.site

SEO Results Orchestrators

SEO Results Orchestrators / November 15, 2023 at 21:34 pm

Is your SEO toolkit missing a crucial element for achieving unparalleled success? Look no further! ProRankTracker is the answer to enhancing your SEO game and ensuring your success in the digital landscape.

**Get Highly Specialized SEO Rank Tracking & Reporting**: https://marketbeast.site/proranktracker

Here's why ProRankTracker is the missing link in your SEO tools arsenal:

**Tracking:**
1. **100% Accurate SERP Rank Tracking:** Enjoy reliable rank tracking from anywhere, using any device.

**Analyzing:**
2. **Online Views, Data Visualizations, and Charts:** Evaluate SEO progress and make informed decisions based on valuable insights.

**Reporting:**
3. **Revolutionize Your Reporting Options:** Automatically generate and send customized, white-label reports.

**Benefits:**
- **Unlimited Saved Historical Ranking Data:** Keep track of your SEO journey effortlessly.
- **Unlimited Sub-Accounts:** Included with all Agency plans for seamless team collaboration.
- **Unbeatable Pricing:** Large-tracked terms quotas with the flexibility to customize.
- **Unlimited Branded Reports:** Increase trust and retention with your clients.
- **Enhanced Productivity:** Schedule reports for efficiency and use live updated reports for client convenience.
- **Multilingual Reports:** Available in 13 languages for accurate client communication.
- **Dedicated Support:** Receive extreme support from customer success managers.
- **API Access:** Build powerful integrations for a comprehensive SEO strategy.

While popular All-in-One tools may offer basic position tracking, ProRankTracker specializes in rank tracking and reporting. We adjust to search engine changes faster than anyone else, ensuring 100% accuracy in our reports. Can the all-in-one guys say that? No, they can't.

ProRankTracker is dedicated to providing you with more "views" and customizable options than any other rank tracking tool. Our invaluable reporting helps you analyze data and gain a deeper understanding of the effectiveness of your SEO efforts.

Did you know that most ProRankTracker users also have accounts with popular all-in-one SEO tools? We bridge the gap between big-picture SEO and detailed insights, proving value and building trust with your clients.

ProRankTracker is the essential tool for SEO agencies and professionals. We help you stay on top of things and ensure your clients' satisfaction!

**Unlock SEO Success Today**: https://marketbeast.site/proranktracker

fgh

fgh / February 27, 2023 at 14:04 pm

fgh

Celestina Jordan

Celestina Jordan / January 5, 2023 at 12:53 pm

Hi Admin,

I wanted to introduce myself in a way that shows I’m interesting, witty and clever. Alas, I wrote this email instead.

I come bearing just what you’ve always wanted, another pitch! I’ll get this over as quickly as possible.

Are you accepting link insertions in old blog posts on your website?

If yes, how much would you charge for this?

If not, will you be interested in a 3-way link exchange that can help boost your website ranking?

Consider my fingers, toes and all appendages crossed!

Cheers,
Celestina Jordan
Craigs 9

Matt Caudill

Matt Caudill / March 18, 2022 at 02:00 am

Hi,

I wanted to introduce myself in a way that shows I’m interesting, witty and clever. Alas, I wrote this email instead.

I come bearing just what you’ve always wanted, another request! I’ll get this over as quickly as possible.

Are you accepting link insertions in old blog posts on your website?

If yes, how much would you charge for this?

If not, will you be interested in a 3-way link exchange that can help boost your website traffic?

Consider my fingers, toes and all appendages crossed!

Cheers,
Celestina Jordan
Chief Dreamer
Craigs9

Add your comment

Captcha

    Please, be polite and helpful and do not spam or offend others! We promise you will be treated the same way!

    Log in to your account to post your comments. If you still haven't joined our community yet, you can create your FREE account now!

    Posting tip:
    If you use code in your comments, please put it in these tags [php], [sql], [css], [js] PHP code example: [php] echo date("Y-m-d"); [/php]

    Thank you,
    PHPJabbers Team

    PHP Scripts

    Check our extensive collection of top-notch PHP Scripts that will enhance your website!


    Commercial PHP scripts

    Free Scripts

    Add great new functionalities to your website with our Free Scripts collection.


    Free scripts