PHP mail() Function Code to Send Emails from a Form

You can use the PHP mail() function to send an email with PHP and the simplest way to do this is to send a text email when a visitor to your website fills out a form.

(Since you’re interested in sending email via PHP, we’re assuming you have a live website. Is that not the case? Let’s start by getting you hooked up with the perfect web hosting package.)

Basic PHP email() function code

Below is the code for the basic email function. We can take the script and use a form on our website to set the variables in the script above to send an email.

<?php //if "email" variable is filled out, send email   if (isset($_REQUEST['email']))  {      //Email information   $admin_email = "someone@example.com";   $email = $_REQUEST['email'];   $subject = $_REQUEST['subject'];   $comment = $_REQUEST['comment'];      //send email   mail($admin_email, "$subject", $comment, "From:" . $email);      //Email response   echo "Thank you for contacting us!";   }      //if "email" variable is not filled out, display the form   else  { ?>   <form method="post">
Email: <input name="email" type="text" />
Subject: <input name="subject" type="text" />
Message:
<textarea name="comment" rows="15" cols="40"></textarea>
<input type="submit" value="Submit" /> </form> <?php } ?>

1. The first part of the form checks to make sure the email input field is filled out. If it isn’t, displays the HTML form on the page. If the email is set (after the visitor fills out the form), it is ready to send.

2. When the submit button is pressed after the form is filled out, the page reloads, reads that the email input is set and it sends the email.

Keep in mind, this is a basic tutorial explaining how to use the mail() function in PHP but it can be insecure and you should generally avoid using it. The purpose of this article is to provide you the basics of how to use phpmail() but if you want to do more with it, you may want to look into securing your code to possible hacks.

To learn more about the PHP email function, please see the article on How to create a custom PHP contact form with more information on validation and error checking. If you need further assistance, feel free to ask a question on our support center.

Thoughts on “PHP mail() Function Code to Send Emails from a Form

  • Greetings self/master coders all over!

    My  issue is… 

    I have a HTML form with 7 inputs(email,name and 5 type=number)…good. I have “connected” the form with “action=insert.php” file(i have already a script that connect to mi database, and saves that informations)…

    NOW…the problem is that i CAN`T make to send a “copy” of that form to the user who fill the form( i used this  code to do it so i can receive, and is awsome!), but my self-learned skills(thnx again to open source and tnx to you too!)

    Any further help will be “compensated” with gratitude and a place on my Landingpage when released(footer 33%width,250pxheight). 

     

  • i use your code. only change $admin_email=”mygangkrish@gmail.com”

    but it show error

     

    ( ! ) Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp\www\Newfolder\shoppers\mail.php on line 12

    <?php

    //if “email” variable is filled out, send email

      if (isset($_REQUEST[’email’]))  {

      

      //Email information

      $admin_email = “mygangkrish@gmail.com”;

      $email = $_REQUEST[’email’];

      $subject = $_REQUEST[‘subject’];

      $comment = $_REQUEST[‘comment’];

      

      //send email

      mail($admin_email, “$subject”, $comment, “From:” . $email);

      

      //Email response

      echo “Thank you for contacting us!”;

      }

      

      //if “email” variable is not filled out, display the form

      else  {

    ?>

     

     <form method=”post”>

     

      Email: <input name=”email” type=”text” />

     

      Subject: <input name=”subject” type=”text” />

     

      Message:

     

      <textarea name=”comment” rows=”15″ cols=”40″></textarea>

     

      <input type=”submit” value=”Submit” />

      </form>

      

    <?php

      }

    ?>

    • The error says it’s failing to connect at port 25. You may need to change the port. Check with your provider for the available ports to use for your email server. Typically, the alternative is 587, but you should check with your provider for the proper port to use.

  • This is my site

    mnjewellers.com

    Can you select one item and add to cart, then go to top cart icon having checkout just click that CHECKOUT.. i am getting below error

     

    Warning: fsockopen(): unable to connect to ssl://smtp.gmail.com:25 (Connection refused) in /home/hnoxs9t5s33x/public_html/system/library/mail/smtp.php on line 87

     

    recently my friend config Gsuite its works well, not sure suddenly what happend couple of days back its not working.

     

    Can you help me out of this.

     

    • Most likely, the port 25 is blocking the traffic, which is common when it thinks the traffic coming through is spam or insecure. Try using the secure settings for SMTP for the server. Typically, the secure server port for SMTP is 465. Change that setting and also make sure you’re using the secure setting for SMTP. You can see an example of the settings in this article.

  • How to run PHP code in background ?

    If click a button to send a mail but the gmail.php run in background how?

    pls ans me.

     

    • If you’re not familiar with coding, then we highly recommend that you speak with an experienced developer to properly (and securely) provide code for your website. PHP code is actively running when you open a page. If you have a link that is set to run a page which includes a PHP script, then that script runs when that page is opened. If you want more information on how a PHP script is executed, see this post. We recommend that you speak with an experienced developer because it is very easy to create PHP scripts that are vulnerable to being hacked if you are not properly versed in plugging the holes that an online script can include. You are ultimately responsible for the security of your website, so we encourage safe and secure practices for that purpose.

  • how to fix error ? 

    ! ) Warning: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in C:\wamp64\www\PlayGround\Test Project\index.php on line 12

  • this Error Show 

    Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing in C:\xampp\htdocs\form.php on line 14
    Error: Please try again later

    • Your error indicates that you’re using a XAMPP server for the script. A mail server setting is required in your php.ini in order for the script to work. We also primarily provide support for our hosting servers. Please consult with an experienced programmer or the XAMPP documentation in order to learn how to set the mail server settings for your local installation.

  • Greetings! I was asked to change the email to where this internal HTML widget txt form gets sent. In my efforts, I removed the <form action> line of code before saving it…I know, rookie mistake. I am now having an issue whith where to locate this command in php…where can I find it? Its an internal form built in widget txt to send email to admin when filled out. The bold line is what was deleted, I simply put in what I thought it was but there is no way of telling. Any help on direction to find form action command would be AMAZING! Thank you.

    <form action=”/submit_admin.php” method=”post” onsubmit=”return validateContactForm()” id=”form1″>

    <input type=”hidden” value=”9088″ id=”email” name=”email”>

    <input type=”text” style=”display: none;” id=”last” name=”last”>

    <input type=”text” onblur=”if (this.value == ”) {this.value = ‘Name’;}” onfocus=”if(this.value == ‘Name’) {this.value = ”;}” value=”Name” id=”name” name=”name” style=”width: 94%; margin-left: 6px; margin-top: 6px; font-size: 11px;” class=”txtBox”><BR>

    <input type=”text” onblur=”if (this.value == ”) {this.value = ‘Email Address’;}” onfocus=”if(this.value == ‘Email Address’) {this.value = ”;}” value=”Email Address” id=”email2″ name=”email2″ style=”width: 94%; margin-left: 6px; margin-top: 6px; font-size: 11px;” class=”txtBox”>

    <input type=”text” onblur=”if (this.value == ”) {this.value = ‘Phone’;}” onfocus=”if(this.value == ‘Phone’) {this.value = ”;}” value=”Phone” id=”phone” name=”phone” style=”width: 94%; margin-left: 6px; margin-top: 6px; font-size: 11px;” class=”txtBox”>

    <input type=”text”  id=”address” name=”address” style=”width: 94%; margin-left: 6px; margin-top: 6px; font-size: 11px;” class=”txtBox”><BR>

    <textarea onblur=”if (this.value == ”) {this.value = ‘Brief description of your legal issue’;}” onfocus=”if(this.value == ‘Brief description of your legal issue’) {this.value = ”;}” 

    value=”Brief description of your legal issue” style=”width: 93%; margin-left: 6px; margin-top: 6px; font-size: 11px; font-family: Tahoma; height: 85px;” class=”txtArea” id=”description” name=”description”>Brief description of your legal issue</textarea>

    <BR><input type=”checkbox” name=”confirm” value=”1″ style=”margin-left: 6px;”> I have read <a href=”/disclaimer”>the disclaimer.</a><BR>

    <input type=”image” src=”/submit.png” id=”submit” style=”margin-top: 15px; float: right; margin-right: 10px;”>

    </form>

     

    • The form action is typically a reference to a file that is on your web server. So, if you look at your files and try to find the path, then you should be able to find that file. If all else fails, if you are a customer of InMotion Hosting, you can call into our live technical support team, and they can help you find the file.

  • This code working fine on my web site.

    But this form sending notification only to admin mail. 
    how do i send copy to user as well

    thanking for your error free code

    • I recommend reviewing your Exam mail log to determine what is happening with the email that is being sent. Also, be sure that you are using an email account associated with your domain as the email address the script is sending FROM. This will ensure that the authentication will succeed to deliver the email. If you determine any errors from the logs, feel free to let us know more details, we may be able to assist you further. I hope this helps!

  • Sir thanx for the code..

    Sir this code works very well on local host, but it doesnt work when I upload this code on the website server.

     

  • Sir,

    Thank you for a code.

    Code works perfectly on localhost but when i upload it to my website server, I did not get any mail.

     

  • My php script is working, but after I send a message it dispalys “thank you”(what I wrote in echo) and that is fine, but I have to manualy go back to my website and I think that is not the good practice. What should I do to make it go back to website as soon as the message is sent? thank you

    • You can not to that with PHP, you can have a button that says go back and set the href to whatever url you want the user to go to, you can also add javascript to the bottom of the page like the example below and that will automati