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
$to = "[email protected]";
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$message = $_REQUEST['message'];

//Send email
mail($to, $subject, $message, "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="message" rows="15" cols="40"></textarea>
<input type="submit" value="Submit" />
</form>
<?php } ?>

If you want to include multiple recipients on the email, you can update this line as follows:

$to = "[email protected], [email protected]";

How PHP mail() works

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.

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.

Leveraging PHPMailer for Advanced Email Functionality

In addition to utilizing the native PHP mail() function for sending emails from your web forms, you have the option to explore more advanced email capabilities through a third-party library known as PHPMailer.

While this article has primarily focused on demonstrating the usage of the mail() function, it’s worth noting that PHPMailer offers an array of features that can greatly enhance your email sending process. If you find yourself in need of secure SMTP authentication, streamlined attachment handling, or comprehensive error reporting, considering PHPMailer as an alternative solution could provide you with the tools to address these requirements seamlessly.

Conclusion

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.

Carrie Smaha
Carrie Smaha Senior Manager Marketing Operations

Carrie enjoys working on demand generation and product marketing projects that tap into multi-touch campaign design, technical SEO, content marketing, software design, and business operations.

More Articles by Carrie

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

  1. hi there,
    I using this code and it is working fine locally, but i want to know how can I attach a file with my mail so the i can send the file too to the receiver.
    please help me.

    1. Hello Asad,

      I looked this up and it appears adding a file attachment is fairly involved. The comments I found say that it’s better to go and use the latest features of the PHP Mailer script that you can find here: https://github.com/PHPMailer/PHPMailer. Hope that helps!

  2. 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). 

     

  3. i use your code. only change $admin_email=”[email protected]

    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 = “[email protected]”;

      $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 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.

      1. Hello Richtech,

        Sorry for the problem with the PHP mail function. The error is either a result of incorrect validation through the SMTP information, or it may be that the port is being blocked. Try changing the port to 587 and see if the issue persists. If the problem continues, then you can work with our live technical support team. They can directly access your server to look at the logs and then see if the issue is server-related.

      1. Hello export,

        Thank you for your comment. If you are looking to use PHP to create a form to send emails, I recommend following the instructions on this guide:

        https://www.inmotionhosting.com/support/website/how-to-create-a-custom-php-contact-form/

        Please let us know if you have any further questions and we will be happy to help!

        Best Regards,
        Alyssa K

  4. 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.

     

    1. 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.

  5. 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.

     

    1. 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.

    1. I recommend checking the information you are using for your mail server. More specifically, check the port and hostname to make sure they match your server’s configuration.

  6. 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

  7. 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

    1. 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.

  8. 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>

     

    1. 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.

  9. 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

    1. 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!

  10. 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.

     

  11. 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.

     

  12. 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

    1. 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 automatically take them to the specified URL.

      “window.location.href = ‘example.com/random.html’;”

  13. Hello, 

    I have developed a website for a client and am about to make it live on a domain. So, the aforementioned mail function would work for a website running on a domain server? I mean it is not asking for a password or anything. How is it going to send a mail from an email account without logging into it? 

    1. Hello,

      Thanks for the question on PHPMail. You can see a discussion on this issue in this forum post. It’s basically a function of php Mail (you can look up the function on the documentation for the mail function in PHP for more details). It doesn’t really access an email account the same way you think of it when using an email client. It should be noted that mail sent from PHP Mail functions tend to be blocked because of the lack of verification. In order to avoid this, we advise on using SMTP parameters . You can see this in our tutorial here.

      If you have any further questions, please let us know.

      Kindest regards,
      Arnel C.

  14. hi,I’m having a problem while getting mail.code did’t showing any errors but I’m not receiving any mails.(spam list searched) 

    can you help me?

    1. I recommend checking your mail logs for records of the transmissions or errors. We are happy to help troubleshoot further. Can you provide a link to the form for us to test?

      Thank you,
      John-Paul

  15. I am having trouble with my form

    <?php

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

     

        // EDIT THE 2 LINES BELOW AS REQUIRED

        $email_to = “[email protected]”; 

        $email_subject = “Arabella Lead-Message from New Client!”;

     

        function died($error) {

            // your error code can go here

            echo “We are very sorry, but there were error(s) found with the form you submitted. “;

            echo “These errors appear below.<br /><br />”;

            echo $error.”<br /><br />”;

            echo “Please go back and fix these errors.<br /><br />”;

            die();

        }

     

        // validation expected data exists

        if(!isset($_POST[‘name’]) ||        

           !isset($_POST[’email’]) ||     

           //!isset($_POST[‘subject’]) ||

           !isset($_POST[‘phone’]) ||

           //!isset($_POST[‘message’]))

            {

            died(‘We are sorry, but there appears to be a problem with the form you submitted.’);       

        }

     

        $name = $_POST[‘name’]; // required

        $email = $_POST[’email’]; // required    

        //$subject = $_POST[‘subject’]; // required

        $phone = $_POST[‘phone’]; // required

        //$message = $_POST[‘message’]; // required

     

     

        $error_message = “”;

        $email_exp = ‘/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/’;

      if(!preg_match($email_exp,$email)) {

        $error_message .= ‘The Email Address you entered does not appear to be valid.<br />’;

      }

        $string_exp = “/^[A-Za-z\s.’-]+$/”;

      if(!preg_match($string_exp,$name)) {

        $error_message .= ‘The Name you entered does not appear to be valid.<br />’;

      }

      //if(!preg_match($string_exp,$subject)) {

        //$error_message .= ‘The Last Name you entered does not appear to be valid.<br />’;

      //}

      if(strlen($message) < 2) {

        $error_message .= ‘The Comments you entered do not appear to be valid.<br />’;

      }

      if(strlen($error_message) > 0) {

        died($error_message);

      }

        $email_message = “Form details below.\n\n”;

     

        function clean_string($string) {

          $bad = array(“content-type”,”bcc:”,”to:”,”cc:”,”href”);

          return str_replace($bad,””,$string);

        }

     

        $email_message .= “Name: “.clean_string($name).”\n”;

        $email_message .= “Email: “.clean_string($email).”\n”;

        //$email_message .= “Subject: “.clean_string($subject).”\n”;

        $email_message .= “PhoneNumber: “.clean_string($phone).”\n”;

        //$email_message .= “Message: “.clean_string($message).”\n”;

     

    // create email headers

    ‘Reply-To: ‘.$email.”\r\n” .

    $headers = ‘From: ‘.$email.”\r\n”.

    ‘X-Mailer: PHP/’ . phpversion();

    @mail($email_to, $email_subject, $email_message, $headers);

     

    sleep(1);

    echo “<meta http-equiv=’refresh’ content=\”0; url=https://test.rafikiweb.com/thanks.html\”>”; //Add a thankyou page with a Close button.

    ?>

     

    <?php

    }

    ?>

     

     

     

    1. Hello,

      Apologies for problems with the phpMail form that you’re using. If you’re modifying our code we cannot go through your code to assess it as that is beyond our scope of support. My advice is to either consult with an experienced programmer or to post in a forum where the community can help to assess your code and determine where it is failing.

  16. Hi, my mail() code is:

     

    mail($email,$subject,$message);

    With $email cnntaining the address I want to send TO so that people can reply to it to verify their e-mail.  But it doesn’t send. It DOES send when I use simply “[email protected]” in place of $email.  Any thoughs? Thanks!

    1. The code provided is strictly for the send mail string to be:mail($admin_email, “$subject”, $comment, “From:” . $email);. If you’re making changes to it, then you have to change the other parts of the code to match and we do not normally provide coding support. My advice is use our format and change the email address as identified in the code. If you need something further, then you may need to get advice from a developer or look in related community forums.

  17. Hi,

     i have to work the mail send concept in the PHP but i have the error for (

     mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in

    ) how to correct the error please help and solve the problem.

    Thanks in advance

    1. As a test, try using port 587, instead of port 25. If your problems persist, try using your secure settings over port 465.

      Thank you,
      John-Paul

  18. Hello, im trying to creat a web site and now i want to make emails to work, but i dont have any SMTP server. So do you have any link to good tutorial or something like that? 
    Thank you. 🙂

  19. i get this every time

    Warning: mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.

    whats wrong? 
    thanks

    1. The SMTP error indicates that the connection to SMTP that is configured does not match the proper settings for this to function properly. I would suggest reviewing your SMTP settings and try again. You can also try to make sure your PHP mail() function is in your php.ini file, by adding:

      sendmail_path = /usr/sbin/sendmail -t -i

      to the very top of your php.ini file.

    1. Hello Vishnu,

      We would need more clarification of the issue. Please provide more information about how you’re using the PHP mail function to send mail and why you’re having issues with sending mail using “[email protected]” we may need specific domain information. If you want to have this issue resolved privately, then please contact our live technical support team. They can work with you directly (if you are an InMotion customer) and resolve the issue quickly.

      If you have any further questions, please let us know.

      Kindest regards,
      Arnel C.

    2. I am using the mail function in conjunction with dreamweaver vaiables. I have a shared hosting plan and the emails all send fine except when they are recived they come form****[email protected] not with my domain eamil address ****@ssfhl.com. Is there a way to change that?

    3. This article provides an example of the mail function can be used, but custom coding will be necessary to work properly with your site.

    4. PHP mail function uses the server to send mail. Seeing the mail from address like this is normal. You would need to set up SPF records and Domain Keys so you could send email as the domain. Here’s the explanation from php.net. And here’s an article on SPF records

  20. Nice tutorial. This tutorial was really simple and useful to send the email to users on my new business site.Its useful to beginners.

    Thanks.,

  21. Hello! Will sendmail PHP function work for Adobe Muse upload forms like this upload widget

    They say it can not work sometimes in another hosting providers and I’m worried about it.
     
    Thanks
    1. Hello Chris,

      The sendmail function should work. If you’re having problems with it, it’s possible that the security rules on the server may be interfering. You can actually turn off these rules in the cPanel (to an extent). If it doesn’t work beyond that, then you should contact our live technical support team for assistance.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  22. Unless you have a mail server also set up on your local machine, it will give you an error. This is not something that is easy to do. You may want to check into testing tools such as the one at https://www.toolheap.com/test-mail-server-tool/ that may help you.

  23. Hello,

    It’s working, but my contact form input fieds are as below:

    Name, Email, Subject, Message.

    When i fill the form and submit, the name input does not appear in the mail.

    Please what should i do. Standing by for your help. Thanks.

  24. Hi , 

    thank you, it works . But the mesage is not encrpted can u plz tell how it can be encrypted and secure.

    Thank you,

    1. Hello Sai j,

      Thanks for the question about the encrypted email using phpMail. You would need to add code to send it as an encrypted email. Please see this link for possible solutions for your request.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  25. Hi Guys, 

    Thanks for the great job.

    The form works alright, except that the senders email address is not included  in the body of message sent to me. Also, how best can I include additional field, such as 

    Phone number and website address?

     

    Thanks.

     

    1. The sender of the email is the server, so that should be in the email. If you mean the email address they are supposed to supply in the form, check the code to make sure it is correct. As for adding a new field, just copy one of the form fields and adjust it for the desired field you want, like a phone number.

  26. Hello @caseyb

    Thanks for your response, but this was not my question… In WordPress their are filters to do what you suggested. Let me explain it with an example.

    Your email is [email protected], and you’re filling out the contact form on my blog. When I receive your mail in my inbox, the wp_mail() function generates a $header like so : From : WordPress : [email protected]

    My question is how to get the sender email instead ?
    How to get your email, the email that you entered in the input field : [email protected] ?

    Thanks again

    1. LebCit, I’m sorry that I misunderstood your question, but I think I do now. In that case, the following should work:

      $headers .= "From:  $_POST['email']";
      $headers .= "Reply-to: $_POST['email']\r\n";

      However, please keep in mind that I am not a developer, this may not actually function as expected, and you may wish to consult one that is significantly more familiar with PHP for this.

  27. Hello,

    Thanks a lot for this helpful code. While testing it with wp-mail like so :

    <?php
    //if "email" variable is filled out, send email
    if (isset($_POST['email']))  {
        //Email information
        $to = get_option( 'admin_email' );
        $headers = $_POST['email'];
        $subject = $_POST['subject'];
        $message = $_POST['message'];
    
        //send email
        wp_mail($to, $subject, $message, $headers);
    
        //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" /><br />
        Subject: <input name="subject" type="text" /><br />
        Message:<br />
        <textarea name="message" rows="15" cols="40"></textarea><br />
        <input type="submit" value="Submit" />
     </form>
    
    <?php
      }
    ?>

    Everything works well, thank you.

    Just a question.

    How would I set it so when I receive the mail, the header of the message would be at least the email of the sender and not the generated wordpress@$sitename ?

    Thanks in advance for you help.

    Wish to see some dedicated WordPress ‘advanced’ tutorial.

    Thanks again

  28. Thanks for the tutorial you are doing great here.

    I want a situation whereby I will type the email address I want to send message to just like you are using gmail to send message.Can I use this code for it? because I notice here the email is static. Pls kindly help me out

    1. Hello Optimum,

      The code is fro using PHP mail only. We do not provide coding support as it is beyond the scope of our support. If you’re looking to send emails via Gmail, then you may need to seek a different forum that provides code for that kind of request.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  29. please the code did not work for me

    it says Warning: mail(): “sendmail_from” not set in php.ini or custom “From:” header missing in C:\xampp\htdocs\MyApp\Assignment1.php on line 14
    Thank you for contacting us!

  30. I am using PHPMailer to send email. It was working fine for some days. But now i am facing problem that on that id emails are coming blank automatically in a large quantity (Like 10-15) without data (which gets filled with variables value from form). Only labels are coming. But if user is sending thru form filled up then every thing is ok. I am not able to find how and why theses emails are coming??

     

    Please guide.

     

     

  31. I just created a website for my company but in that when we are sending the mail its not coming i dont know why its not working

    <?php

    $to=”******@gmail.com”;

    require ‘PHPMailer/PHPMailerAutoload.php’;

    $mail = new PHPMailer;

    //$mail->isSMTP();

    $mail->Host = ‘smtp.mycompany.com’;

    $mail->SMTPAuth = true;

    $mail->Username = ‘[email protected]’;

    $mail->Password = ‘password’;

    //$mail->SMTPSecure = ‘tsl’;

    $mail->Port       = 25;   

    $mail->SMTPDebug = 4;              

    $mail->From = $email;

    $mail->FromName = $name;

    $mail->addAddress($to, ‘Enquiry’);$mail->AddCC(‘[email protected] ‘, ‘pavi’);

    $mail->addReplyTo($email, $name);

    $mail->WordWrap = 50;

    $mail->isHTML(true);

    $mail->Subject = $sub;

    $mail->Body    = $comments;

    if(!$mail->send()) {

       echo ‘Message could not be sent.’;

       echo ‘Mailer Error: ‘ . $mail->ErrorInfo;

       ?>

       <script type=”text/javascript”>window.location.href = “index.php”</script>

    <?php

    }

     ?>

    <script type=”text/javascript”>window.location.href = “index.php”</script>

    1. Check our email username and password by logging into your email. Also, review your error logs, and mail logs for additional clues.

      Thank you,
      John-Paul

  32. this code is not working.plz correct it.

     

    <?php

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

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

      

      //Email information

      $admin_email = “[email protected]”;

      $email = $_REQUEST[’email’];

      $subject = $_REQUEST[‘subject’];

      $comment = $_REQUEST[‘comment’];

      

      //send email

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

      

      if(isset($_REQUEST[“frsb”]))

      { 

            

                require_once “Mail.php”;  

                $from    = “[email protected]”;  

                $to      = $email1; 

                $subject = ” msg sent!!”;  

                $body    = ” You’ve successfully. Your password is $fr3 .\n

                            Thankyou.

                            “;

     

                /* SMTP server name, port, user/passwd */  

                $smtpinfo[“host”] = “ssl://smtp.gmail.com”;  

                $smtpinfo[“port”] = “465”;  

                $smtpinfo[“auth”] = true;  

                $smtpinfo[“username”] = “[email protected]”;  

                $smtpinfo[“password”] = “9830565226”;  

     

                $headers = array (‘From’ => $from,’To’ => $to,’Subject’ => $subject);  

                $smtp = &Mail::factory(‘smtp’, $smtpinfo );  

     

                $mail = $smtp->send($to, $headers, $body);  

     

                if (PEAR::isError($mail))

                    {  

                  echo(“<p>” . $mail->getMessage() . “</p>”);  

                 } 

                 else {  

                   

                    echo “<script>alert(‘Password has been sent to your mail.’);</script>”;

                 }

           

        }

     

      //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” /><br />

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

      Message:<br />

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

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

      </form>

      

    <?php

      }

    ?>

    1. Hello Monalisa,

      We’re sorry that you’re having problems with the code that you are using. We generally do not provide coding support. If you are using our code to the letter, then it should be working, but you are using a variant of the code and we cannot troubleshoot that for you. You may want to present this issue in a coding forum or ask a developer to review the code for you. Apologies that we cannot correct the issue for you.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

    1. Hello JeoofDC,

      Sorry for the problem with the email not appearing. We would need more information on the account and your settings if you need further assistance. Also, remember that any email may have been affected by Spam filters or rules if you have any. If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  33. Hello, this doesn’t work for me, I’ve done everything perfectly.

    I’ve heard things have changed, is it possible that this is no longer valid?

    1. Hello Minhaj,

      This has been tested recently and has been functioning. If you are having problems, please make sure to check what errors you’re getting. The issue may not be related to the code.

      If you have any further questions, please let us know.

      Kindest regards,
      Arnel C.

  34.  Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set()

  35. Hey,

    I used this mail function but I got a problem with it. When I sended a E-mail it and I want to refresh the page it gets a pop-up. When I click at ok, it will send the mail once again.. How can I fix this?

  36. Thanks TJ! I am still having a problem though. Could you take a look at my code here:

    html code:

                  <form id=”main-contact-form” name=”contact-form” action=”sendemail.php?do=send” method=”post”>

                    <div class=”row  wow fadeInUp” data-wow-duration=”1000ms” data-wow-delay=”300ms”>

                      <div class=”col-sm-6″>

                        <div class=”form-group”>

                          <input type=”text” name=”name” class=”form-control” placeholder=”Name” required=”required”>

                        </div>

                      </div>

                      <div class=”col-sm-6″>

                        <div class=”form-group”>

                          <input type=”email” name=”email” class=”form-control” placeholder=”Email Address” required=”required”>

                        </div>

                      </div>

                    </div>

                    <div class=”form-group”>

                      <input type=”text” name=”subject” class=”form-control” placeholder=”Subject” required=”required”>

                    </div>

                    <div class=”form-group”>

                      <textarea name=”message” id=”message” class=”form-control” rows=”4″ placeholder=”Enter your message” required=”required”></textarea>

                    </div>                        

                    <div class=”form-group”>

                      <button type=”submit” class=”btn-submit”>SUBMIT MESSAGE</button>

                    </div>

                  </form>   

     

    Here’s the corresponding .php code:

    <?php

    header(‘Content-type: application/json’);

    $status = array(

    ‘type’=>’success’,

    ‘message’=>’Email sent!’

    );

     

        $name = @trim(stripslashes($_POST[“name”])); 

        $email = @trim(stripslashes($_POST[“email”])); 

        $subject = @trim(stripslashes($_POST[“subject”])); 

        $message = @trim(stripslashes($_POST[“message”])); 

     

        $email_from = $email;

        $email_to = “[email protected]”;

     

        $body = ‘Name: ‘ . $name . “\n\n” . ‘Email: ‘ . $email . “\n\n” . ‘Subject: ‘ . $subject . “\n\n” . ‘Message: ‘ . $message;

     

        mail($email_to, $subject, $body, ‘From: <‘.$email_from.’>’);

     

        echo json_encode($status);

        die;

     

     

    **Whenever I test the submit button, the email receiver just receives a blank email like this:

    (no subject)

    Name:

    Email:

    Subject:

    Message:

     

    that’s it nothing else, information typed in the form are missing.

    1. While we can assist with your individual error responses, we are not able to set up a testing environment to locate specific errors within code itself.

  37. hi there! If I created my sendemail.php in a separate file, where should I insert the link for it in my html file? Also should I change the file extension of my webpage into .php also or it the sendemail.php file can also run in .html webpage? sorry, I am new about this thing. Thanks!

    1. Hello Jon,

      We would suggest setting the file extension to .php as html code can run in PHP files outside of the PHP start/end tags. Also you do not put a link in the parent index for sendmail.php, you would set the forms action attribute to action=”sendmail.php” as shown in the example in this article.

      Best Regards,
      TJ Edens

  38. I am getting the error in the mail function when i am using the more number of fields to be sent by email.I am getting like some T_STRING error in the files.

    Below is my code

    <?php

    $firstname=$_POST[‘FirstName’];

    $lastname=$_POST[‘LastName’];

    $address=$_POST[‘Address’];

    $state=$_POST[‘State’];

    $zipcode=$_POST[‘ZipCode’];

    $homephone=$_POST[‘HomePhone’];

    $cellphone = $_POST[‘CellPhone’];

    $visastatus = $_POST[‘VisaStatus’];

    $email1=$_POST[‘Email1’];

    $hourlyrate=$_POST[‘HourlyRate’];

    $salaryrequired=$_POST[‘SalaryRequired’];

    $relocation=$_POST[‘Relocation’];

    $availability=$_POST[‘Availability’];

    $nickname=$_POST[‘NickName’];

    $title=$_POST[‘Title’];

    $avlSKILLCODES=$_POST[‘avlSKILLCODES’];

    $txa1=$_POST[‘txa1’];

       

    $toaddress = “[email protected]”;

           $subject = “New Candiadte”;

     

    $all=

    “FirstName: “.$firstname.”\\r\

     

    LastName: “.$lastname.”\\r\

     

    Address: “.$address.”\\r\

     

    ZipCode: “.$zipcode.”\\r\

     

    HomePhone: “.$homephone.”\\r\

     

    CellPhone: “.$cellphone.”\\r\

     

    VisaStatus: “.$visastatus.”\\r\

     

    Email1: “.$email1.”\\r\

     

    HourlyRate: “.$hourlyrate.”\\r\

     

    SalaryRequired: “.$salaryrequired.”\\r\

     

    Relocation: “.$relocation.”\\r\

     

    Availability: “.$availability.”\\r\

     

    NickName: “.$nickname.”\\r\

     

    Title: “.$Title.”\\r\

     

    avlSKILLCODES: “.$avlSKILLCODES.”\\r\

     

    txa1: “.$txa1.”\\r\

     

     

    $mailheaders = “From: $email1 \r\n”;

     

    $headers .= “MIME-Version: 1.0\ “;

     

    $headers .= “Content-type: text/html; charset=iso-8859-1\ “;

     

           mail(“$toaddress”, “$subject”, “$all”, “$mailheaders”);

             echo(“Thank you $firstname for regestring with us “);

    exit();

     

           ?>

     

    Can you please explain where i was going wrong  

    1. Hello Suresh,

      Apologies for the problem with the php mail code. If you’re using our code exactly, then we can offer assistance if there is a problem. However, if you’re using other code, then you may want to present this question in a different forum or to a programmer as providing coding support is beyond our scope. If you have a specific error, then we can look into it a little further.

      Apologies that we can’t provide a direct answer. If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  39. i did exactly as u asked but now how will i check if my code has worked cos a still creating the webside so am still on local host

    so how will i check using local host

    1. You cannot test your code on a local machine unless you are running a full server locally. I suggest moving your stuff to a workable production server and test accordingly.

    1. Hello aditya,

      Thank you for contacting us. You should replace “[email protected]” in the script above with a valid email address. This will allow you to send from this address in the message.

      Thank you,
      John-Paul

  40. hi

    this is siva

    iam the begineer of the php

    i want to write some mail function for the contact form 

    but the above code is not working 

    can u please explain brefely

    1. Hello Siva,

      Are you using the code exactly? Are you getting an error while trying to send the email?

      Best Regards,
      TJ Edens

  41. for the email  to be  sent do you need to have  hosted  the  site ? or it can  just  work  locally  using wamp when there is internet

  42. Hi there! I’m new with PHP and stuff. Just want to ask if I need to change my index.html file to “index.php” for the PHP mail function to work? Thanks a lot!

  43. Thanks for the tutorial… really great!

    when the form is submitted it get the thank you message.  Is there a way to have it redirect to the contact page or better my home page?  or maybe have the thankyou message delivered below the form and leave the user on the page?

  44. sir

     i would not getting sen mail through this php code

    <?php
    function Send_Mail($to,$subject,$body)
    {
    try {
           
    require ‘class.phpmailer.php’;
    $from       = “afhgdfg”;
    $mail       = new PHPMailer();
    $mail->IsSMTP(true);            // use SMTP
    $mail->IsHTML(true);
    $mail->SMTPAuth   = true;                  // enable SMTP authentication
    $mail->Host       = “smtp.gmail.com”; // SMTP host
    $mail->Port       =  25;                    // set the SMTP port
    $mail->Username   = “[email protected]”;  // SMTP  username
    $mail->Password   = “innoexcel@123”;  // SMTP password
    $mail->SetFrom($from, ‘lic’);
    $mail->AddReplyTo($from,’donotreply’);
    $mail->Subject    = $subject;
    $mail->MsgHTML($body);
    $address = $to;
    $mail->AddAddress($address, $to);
    $mail->Send();
        }
        catch(Exception $e) {
      echo ‘Message: ‘ .$e->getMessage();
        }
    }
       

    ?>

  45. please Admin can you write me a php code that can send form in such a format with lines underneath and ip adress included?

     

     

     

    name: xxxxxxxxx
    ————————————–
    email address: xxxxxxxx
    ————————————–
    date: xxxxxx

    ———————————–

    ip address: xxxxxxxx
    1. Hello Jessica,

      Unfortunately we do not provide custom coded solutions however you can use PHP to get the session IP and put it in a variable. Then just echo that variable in your message.

      Best Regards,
      TJ Edens

  46. ·         Move an account to “Email Error” if a number of email notifications fail to reach the recipient. The portal should keep a count of the number of times a consecutive email error occurs – once the number reach a certain limit then the account should be moved.

    1. Hello anshul,

      Thank you for contacting us. The guide above includes the email details in the “//Email information” section above.

      If you have any further questions, feel free to post them below.

      Thank you,
      John-Paul

  47. Form:

    <form id=”main-contact-form” class=”contact-form” name=”contact-form” method=”post” action=”sendemail.php”>
                      <div class=”row-fluid”>
                        <div class=”span5″>
                            <label>First Name</label>
                            <input type=”text” name=”name” class=”input-block-level” required=”required” placeholder=”Your Name”>
                            <label>Contact Number</label>
                            <input type=”text” name=”phone” class=”input-block-level” required=”required” placeholder=”Phone Number”>
                            <label>Email Address</label>
                            <input type=”email” name=”email” class=”input-block-level” required=”required” placeholder=”Your email address”>
                        </div>
                        <div class=”span7″>
                            <label>Message</label>
                            <textarea name=”message” id=”message” required=”required” class=”input-block-level” rows=”8″></textarea>
                        </div>

                    </div>
                    <button type=”submit” name=”submit” class=”btn btn-primary btn-large pull-right”>Send Message</button>
                    <p> </p>

                </form>

     

    sendemail.php:

    <?php
        header(‘Content-type: application/json’);
        $status = array(
            ‘type’=>’success’,
            ‘message’=>’Email sent!’
        );
        if(isset($_REQUEST[‘submit’]))
        {
            $name =$_REQUEST[‘name’];
            $email =$_REQUEST[’email’];
         $phone=$_REQUEST[‘phone’];
            $message =$_REQUEST[‘message’];
             $email_from = $email;
             $email_to =”[email protected]”;

             $body = “Name: ” . $name . “\n\n” . “Email: ” . $email . “\n\n” .”Phone: ” . $phone . “\n\n” . “Message:” . $message;
             if(mail($email_to,”From website”, $body, “From:”.$email_from))
             {
                 echo json_encode($status);
                die;
            }
        }
       

    The above code doesnt show any response, even the button click is not responding. Please Help

    1. Hello Dale,

      Sorry for the problem with your code. We unfortunately do not provide coding support. You may want to consult with a programmer or developer for further assistance. The code we have provided in the article above does function and can be used. Apologies that we can go through your code and point out the problem.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  48. I am new in php I have prefer your guide with script but unable to send mail please help me to sort out this issue…

    1. Hello Anil,

      Sorry for the problems with sending email. We need more details in order to help you. Please provide us more information about the problem such as a URL, what code you’re using, error messages and any steps to duplicate the problem.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  49. hello all…

    i need penalize or fine alert notification through email code in php..

     can anyone help me????? 

    #Scott #Arn plz help me…

  50. Hey, I need your help. I am the beginner in making database but I not really understanding about the language and can make a few interface that links to each other but not connected to data base yet, can yu help me if I using postgresql database, can I use this code?

    1. Hello Nurihidayah,

      Our examples are always written from the mysql perspective so they use mysql or mysqli functions. You will want to find the PostGreSQL equivalents from within the php manual.

      Kindest Regards,
      Scott M

  51. Hi,

    I  am  designed  a web page in that when i click a submit button those  are not going to that page. So how to send those details to domain can you let me know. I used your code that  when i am submit that form it is showing thanks without entering any data only

     

    Thanks and Regards,

    Hari Priyanka

     

     

     

     

     

     

     

     

  52. Hi,

    I  am  designed  a web page in that when i click a submit button those  are not going to that page. So how to send those details to domain can you let me know.

  53. Hi folks, I’m trying to do the opposite from above where I have a section of my website I can send an email to and it will post it on my website. Any suggestions? Ideas how to?

    1. Hello LG,

      While that is certainly possible, we unfortunately do not have any code that does that.

      Kindest Regards,
      Scott M

  54. Email not sending

    I’m on Business plan.

    My Contact form Email system is not working. When I click on Send button, it displays “Sending”. But nothing happens. Developer is saying to ask host to resolve this.

    Please check my contact form and help. Link: https://akhil.xyz

    Thanks.

    Akhil K A

  55. in phishing php.. how can you send the long details to your email, without the details been save in password.txt or any given name,,

    help this my script,, help thanks

    <?php
    $To = ‘[email protected]’;
    $Subject = ‘Send Email’;
    $Message = ‘i want to send the logis details here  example email:hshshshs password: xxxxx ‘;
    $Headers = “From: [email protected] \r\n” .
    “Reply-To: [email protected] \r\n” .
    “Content-type: text/html; charset=UTF-8 \r\n”;
     
    mail($To, $Subject, $Message, $Headers);
    ?>

    please help as soon as possible

    1. Hello,

      Sorry, you’re having problems with your code sending blank messages. Please review the provided code above. If your code matches, then it should not be sending blank messages. If you are using different code, we unfortunately do not provide coding support as it is beyond the scope of our support. You may want check out this forum for a possible answer to your question. It may also be a more appropriate forum if you are using custom code.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

    2. Hello David,

      The form above in the article does work with PHP 5.x systems. If you are trying to accomplish something with phishing then we do not support or discuss these types of attacks.

      Best Regards,
      TJ Edens

  56. hi can any one sugesst me correction as receinvg empty message only

    <?php

         $email_to = ‘[email protected]’;

    $subject = “Contact US”;   

    $name =$_POST[‘flname’]; 

        $email_from = $_POST[’email’]; 

        $message = $_POST[‘message’]; 

    $headers = ‘From: ‘.$email_from.”\r\n”.

    ‘Reply-To: ‘.$email_from.”\r\n” .

    ‘X-Mailer: PHP/’ . phpversion();

        $body = ‘Name: ‘ . $name . “\n\n” . ‘Email: ‘ . $email . “\n\n” . ‘Subject: ‘ . $subject . “\n\n” . ‘Message: ‘ . $message;

    $success=@mail($email_to, $subject, $body, $headers);  

    header(‘Content-type: application/json’);

    $status = array(

    ‘type’=>’success’,

    ‘message’=>’Email sent!’

    );

    //    $success = @mail($email_to, $subject, $body, ‘From: <‘.$email_from.’>’);

    echo json_encode($status);

    //header(“Location: index.php”);

        

    //header(‘Location: https://www.khawabnama.com/index.php’);

        //die; 

     

     

  57. hello.

    please help me how to develop admin panel and connect to subscribe email table in database and admin send mail all user whose list of the table.

    1. Hello Piya,

      Unfortunately we do not offer custom coded solutions, though we will try and answer any specific questions you have.

      Kindest Regards,
      Scott M

  58. Hi Everyone,

    I’m so glad to be here. And I feel like i could be able to get the answer to all my questions.

    I have been struggling for about 3 months right now to get the correct answer.

    This is my question. Is it possible to send Email to each client with their data on the Database? if YES. Then, I have a case where I have fetch data from 3 different tables which I currently JOIN. Now I Have a list of 20 Clients or more that each of them may have 5-10 sites ID. Now as the SQL Query runs, they are I don’t know how to fetch specifics column (Client_ID) and rows(Sites_ID) to send it to their specifics Email Address.

    Here is my php script:

     

    <?php

                                $sqlSelect = “SELECT 

    cl.client_name,

    DATE(jb.date),

    jb.job_number,

    jb.repair,

    st.site_name

    FROM

    job_cards jb

    INNER JOIN

    clients cl ON (cl.client_id = jb.client_id)

    LEFT JOIN

    sites st on (st.site_id = jb.site_id)

    WHERE

    jb.completed =  1 

    AND cl.client_id = jb.client_id

    AND jb.date >= DATE_ADD(DATE(NOW()), INTERVAL – 30 DAY)

    ORDER BY cl.client_name ASC”;

                                    //echo $sqlSelect;

                                    $tresult = mysql_query($sqlSelect);

                                   //THE KEY STARTS HERE

                                    $last = ”;

    //END

                                    while($userData = mysql_fetch_assoc($tresult))

    {

    if($i%2==0)

    $classname = ‘evenRow’;

    else if($i%2==1)

     

                         

                                    ?>

    </thead>

    <tbody>

                                            <tr class='<?php if(isset($classname)) echo $classname;?>’>

                                             

     

     

     

    <td width=250>

    <?php 

    //echo $userData[‘client_name)’]; THE KEY is RIGHT HERE!

     

    if ($last == strtolower($userData[‘client_name’])) {

        echo “&nbsp;”;

    }

    else {

        $last = strtolower($userData[‘client_name’]);

     

        echo mysql_real_escape_string ($userData[‘client_name’]);

    }

    //END of THE KEY

    //echo mysql_real_escape_string ($userData[‘client_name’]); ?>

    </td>

    <td width=100>

    <?php echo mysql_real_escape_string ($userData[‘DATE(jb.date)’]); ?>

    </td>

    <td width=50>

    <?php echo mysql_real_escape_string($userData[‘job_number’]);?>

    </td>

    <td>

    <?php echo mysql_real_escape_string($userData[‘site_name’]);?>

    </td>

    <td>

    <?php echo mysql_real_escape_string($userData[‘repair’]);?>

    </td>

                                              

                                      $to .= “[email protected]”;

    $subject =”Monthly Reports for company”;

     

    $headers .=’MIME-Version: 1.0′ . “\r\n”;

    $headers .= ‘Content-type: text/html;charset=iso-8859-1’ . “\r\n”;

    $headers .= ‘From: System Admin <[email protected]>’ . “\r\n”;//<[email protected]>’

     

    $e = 0 while($last)// == $userData[‘client_name’] { $message .=” Company Name : “.$userData[‘client_name’].”\n”. “Date : “.$userData[‘DATE(jb.date)’].”\n”. “Site : “.$userData[‘site_name’].”\n”. “Description : “.$userData[‘repair’].”\n”; if(mail(‘[email protected]’, $subject, $message, $header)) { $e++; } } echo $e;

    $i++;

    }

    ?>        

     

    how My I fetch specific parent ID information that has many child Multidata and send it to an Email?

    1. Hello Micheal,

      Sorry for the problems with the coding for your email issue. Unfortunately, providing specific coding support is normally beyond our scope of support. However, we do try to point you in a direction that can provide you some assistance. Check out this link to a popular support forum. They may have the answer and the code that you seek for fetching data and then emailing it.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  59. Hello Ashok.

    You may want to check the php official documentation on those settings and how to use them. Also, unless you specifically have set up your XAMPP to also be a mail server you will not be able to use mail functionality on it.

    Kindest Regards,
    Scott M

  60. Can you help me with this code? Please tell me where am i going wrong.

    <?php
    if(isset($_POST[‘B1’]))
    {
    $name     = $_POST[‘T1’];
    $email    = $_POST[‘T2’];
    $comments = $_POST[‘S1’];

    $check_msg = ” Contact Form : “.$name.””;
    $msg='<table width=”500″ border=”0″ cellspacing=”0″ cellpadding=”0″ style=”border:solid 1px #2D96D1;”>
      <tr>
        <td colspan=”2″ style=”background-color:#2D96D1;color:#FFFFFF;padding:5px 0px 5px 20px;text-transform:uppercase;font-weight:bold;font-size:13px;”>’.$check_msg.'</td>
      </tr>
      <tr>
        <td>Name:</td>
        <td>’.$name.'</td>
      </tr>
      <tr>
        <td>Email:</td>
        <td>’.$email.'</td>
      </tr>
      <tr>
        <td>Comments:</td>
        <td>’.$comments.'<br></td>
      </tr>
      <tr>
        <td>&nbsp;</td>
      </tr>
      <tr>
        <td>Thanks<br></td>
      </tr>
       <tr>
        <td>&nbsp;</td>
      </tr>
    </table>’;

             $headers = “MIME-Version: 1.0” . “\r\n”;
             $headers .= “Content-type:text/html;charset=iso-8859-1” . “\r\n”;
             $headers .= ‘From: <‘.$email.’>’ . “\r\n”;
            
             
             $from = $email;
             $to = ;     
             if(mail(“[email protected]”, ” Contact Form : “, $comments, “From: $email”))
             {
             echo ‘<script type=”text/javascript”>alert(“Mail sent”); </script>’;
             }
             else { echo ‘<script type=”text/javascript”>alert(“Not sent”); </script>’; }
              }
    ?>

    1. Hello iadmin,

      This is incomplete as I cannot see anything that has to do with the Thank You. I would need a complete cloned environment to troubleshoot which is something we just are not able to do. We are happy to answer any questions about any errors you get however.

      Kindest Regards,
      Scott M

  61. hello sir

       how to solve it ???

                SMTP server response: 503 This mail server requires authentication when attempting to send to a non-local e-mail address. Please check your mail client settings or contact your administrator to verify that the domain or address is defined for this server

     

      thanks in advance

    1. Hello balaji,

      Thank you for contacting us. The authentication is referring to a username and password for SMTP.

      Typically this will be a full email address, and the password for the email account.

      You can view your email settings in cPanel at any time.

      Thank you,
      John-Paul

  62. Thank you.

     

    The code works but  i am getting the “”thank you for contacting Us” nessage on same page after clicking on submit. I want it to open on another page.

     

    Please help in this regard,

     

    Thanks

    1. Hello Moses,

      You would need to put the action in the form such as *form action=”send.php”* and then on the send.php it would execute the mail script and say your thanks.

      Best Regards,
      TJ Edens

  63. <?php 

    // if there is post

    if(isset($_post)&&!empty($_POST))

    {

    // if there is attachment 

    if(! empty($_POST[‘attachment’][‘name’]))

    {

    // store some variables

    $file_name = $_FILES[‘attachment’][‘name’];

    $temp_file = $_FILES[‘attachment’][‘temp_name’];

    $file_type = $_FILES[‘attachment’][‘type’];

    // get extension of the file

    $base = basename($file_name);

    $extension = substr($base,strlen($base)-4,strlen($base));

    //only these file type is allowed 

    $allowed_extenstion = array(“.doc”,”.docx”,”.pdf”,”.png”,”.zip”,”.jpeg”);

     

    //check that this file is allowed 

    if(in_array($extension,$allowed_extenstion))

    {

    // mail essenstials

    $from = $_POST[’email’];

    $to =”[email protected]”;

    $subject=”Your Attachment File”;

    $message=”this is a test massage”;

     

    //things you need 

    $file = $temp_name;

    $content= chunk_split(base64_encode(file_get_contents($file)));

    $uid-md5(uniqid(time()));

     

    //standard mail headers

    $header =”From:”.$from.”\r\n”;

    $header .=”Reply-To:”.$replyto.”\r\n;”;

    $header .=”MIME-Version:1.0\r\n”;

     

    //declaring we have multiple kinds of email(i.e plain text and attatment)

    $header.=”Content-Type: multipart/mixed; boundary=\””.$uid.”\”\r\n\r\n”;

    $header.=”This is a multi-part meassage in MIME formate.\r\n”;

     

    //plain text part

    $header .=”–“.$uid.”\r\n”;

    $header .=”Content-Type:text/plain;Charset=iso-8859-1\r\n”;

    $header .=”Content-Transfer-Encoding:7bit\r\n\r\n”;

    $header .=$message.”\r\n\r\n”;

    // file attachment

    $header .=”–“.$uid.”\r\n”;

    $header .=”Content-Type:”.$file_type.”; name=\””.$file_name.”\”\r\n”;

    $header .=”Content-Transfer-Encode:base64\r\n”;

    $header .=”Content-Disposition: attachment; filename=\””.$file_name.”\r\n\r\n”;

    $header .=$content.”\r\n\r\n”;

     

    //send the mail

    if (mail($to,$subject,””,$header))

    {

    echo “success”;

    }

    else

    {

    echo “fail”;

    }

    exit();

     

    else 

    {

    echo “File type not allowed “;

     

    }

     

    }

    else 

    {

    echo “no file posted”;

    }

    }

    ?>

    </head>

     

    <body>

     

    <form action=”index.php” method=”post”  enctype=”multipart/form-data”>

    <input  type=”text” name=”email” value=”form”/><br />

    <br />

    <input type=”file” name=”attachment” />

    <br /><br />

    <input type=”submit” value=”send mail” /><br />

    </form>

     

     

     

    In this code what is my error please solve it 

    1. Hello smruti,

      Thank you for contacting us. What happens when you try to run this code?

      Are you getting an error?

      Did you follow the tutorial above?

      Thank you,
      John-Paul

    1. Hello Smruti,

      Thanks for the question, but can you provide more detail about what you’re trying to do? We’re not sure what you referring to as “attachment code” or by “mail my ID”. Please give us a little more info and we would be happy to help if we can.

      Kindest regards,
      Arnel C.

  64. hi . sorry am not good in english ( i have a page php . in the page ther is 3 one for the e-mail and two for the username and the password . i want when some one write his e-mais . the page send his e-mail to my email . how can i do this please ?

    1. Hello anton,

      Thank you for contacting us. I recommend checking your mail logs for any record of transmission. This will help determine if it is failing in the code, or it is being delivered, and the server is rejecting it, etc.

      Thank you,
      John-Paul

  65. do the code on top of this page can send email in local host?? i’m using xampp

    please the code runs smoothly but there’s no email shows up in my emails..

  66. hello,

     

    i want a php script which sends email on customer’s birthday without submiting code.simply means automatic mail sending.

  67. can you please help me i tried the code at the top of these page and it run but no email show up in my yahoo and gmail emails.. heres the code that i tried 

    <html>

    <body bgcolor=”black”>

    <center><font siZe=”200″ color=”white”><br><br><br><br>

    This Websites Contains<br>Unknown Quantity<br></font><font color=”white”>Please Type your E-Mail

    <?php

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

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

      

      //Email information

      $email = “[email protected]”;

      $admin_email = $_REQUEST[‘admin_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” /><br />

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

      Message:<br />

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

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

      </form>

      

    <?php

      }

    ?>

     <form method=”post”><br>

      <input name=”email” type=”text” /><br /><br>

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

      

      </form>

      

    <?php

      }

    ?>

    </body>

    </html>

    can you please help me

    1. You may want to contact Live Support and see if they can identify the email as leaving the server. Then you will be able to work from there.

  68. Sir,

         The mail is not sent with my mail() function coding that is”<?php 

     $to = “[email protected]”;

      $subject = “ABCD”;

      $comment = “Abcdefgh”;

      $header = “From:[email protected] \r\n”;  

      //send email

      $send=mail($to, $subject, $comment, $header);

    if($send)

    {

    echo “Message has been successfully sent”;

    }

    ?>

     “.

    What will be correct mail() function.

    Sir, Please advice me.

  69. i create website and i want to send messages to my contact to their phone i’m  as admin,i need information about that

    1. Hello suma,

      Thank you for contacting us. It is possible to code/develop this in PHP, here is a link to a post where they discuss possible solutions.

      If you are using a CMS such as WordPress, Joomla, or Drupal, they may plugins, or addons for accomplishing this as well.

      Thank you,
      John-Paul

  70. Hi, Thank you. What I am looking for is to send a confirmation code back from someone’s email to a webpage using POST rather than GET. I could code a form to be sent within the email and when they click validate it is a form submit so able to use the POST but I want to avoid using a form.I have no idea of any other way to send it from their computer back to the site as POST so the confirm code is not attached to the URL.  I have my form on the website which collects the user data, I process it with heavy validation and then they are sent an email with a link… I was using a link with the confirm code appended to it and then a GET in the webpage to validate but I have read in several places that is not a good idea yet I cannot seem to find how to get the user from their email back to the webpage without using GET. I am aware of using POST/GET in a webpage form, what I need is to use POST so that the data coming back from the validation email to validate that the person actually joined the website is not visable within the URL.

    Thanks again.

  71. Hi, I have a question that I cannot seem to find an answer for online. Probably because it contains words that give me other info. I have a website that will allow users to sign up to. When they create their new member information, once all validation is done and all is correct it sends them an email with a validation link. They click on the link which then redirects back to the website. This allows for their info to be written in a temp table and once validated written to the actual table and the info from temp table deleted. All works fine except that I have to use the URL they click on to send the validation key back to the website which means acquiring the data via GET rather than POST… I am trying to find out if there is a way to send it via POST so that it is not accessible to eyes through the URL. Any direction to where to look how to do this would be great…. trying to search for information because of the words email, validation, post etc are bringing up everything but what I really want.

    1. You should be able to set a variable with either GET or POST so you can process it. Here is a thread on a popular forum that explains different ways to send variables to a waiting page. That should help you with your situation.

    1. Hello Sunny,

      Unless you have set up your local environment to act as a mail server, it will not do so. You will need to test from a hosting server that can actually send the emails. You may also want to use an emulator such as the one linked below. We have not tested this program nor do we endorse it.

      https://www.toolheap.com/test-mail-server-tool/

      Kindest Regards,
      Scott M

  72. port 25 is open i have checked it 

    and changed it to 465and tryed it but cam to be same erroe port 465 and smtp()

     and how vll we know whether port is open or not

    1. Hello Simhaa,

      We’re not sure where you’re trying to run your code, but check out this post. You may require some server setup that is missing. This article will show you how to check on an port. I hope that helps to answer your question! If you require further assistance, please let us know!

      Regards,
      Arnel C.

  73. hai,i am getting this error

    Warning: mail(): Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set() in D:\wamp\www\s\oc.php on line 13
     can’t get conformation mail 

    1. Hello simhaa,

      Thank you for contacting us. We are happy to help, but will need some additional information.

      Have you checked that port 25 is open on your server? The error suggests this may be the problem.

      Thank you
      John-Paul

  74.  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\icone-cnam\Contact.php on line 51

     

    1. Hello Vijay,

      If you’re missing the OpenSSL extension, it typically has something to do with the PHP.INI file. If you are an InMotion Hosting customer, then there should be a PHP.INI file local to your installation. Check out this post in concerning the issue.

      Regards,
      Arnel C.

    2. Hello Boukeri,

      You should first try changing the port. Port 25 is typically blocked by many ISP’s. Try using 587. If you continue to have a problem with it, then please see your documentation for WAMP. We do not provide support for WAMP issues as they are non-service related. If you were running the code on our server, then the WAMP code should not be referenced in the error message.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  75. Dear Friends,

    i want to send mail from php. but each time i run it in browser it displays error message

    Message could not be sent.Mailer Error: Extension missing: openssl

    i am posting my code below

    <?php
    require ‘PHPMailer/phpmailerAutoload.php’;
    require ‘PHPMailer/class.phpmailer.php’;
    //require’phpmailer/class.phpmailer.php’;
    $mail = new PHPMailer;
     
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = ‘smtp.gmail.com’;                       // Specify main and backup server
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = ‘[email protected]’;                   // SMTP username
    $mail->Password = ‘*************’;               // SMTP password
    $mail->SMTPSecure = ‘ssl’;                            // Enable encryption, ‘ssl’ also accepted
    $mail->Port = 995;                                    //Set the SMTP port number – 587 for authenticated TLS
    $mail->setFrom(‘THIS IS TESTING MESSAGE’);     //Set who the message is to be sent from
    $mail->addReplyTo(‘[email protected]’);  //Set an alternative reply-to address
    $mail->addAddress(‘[email protected]’);  // Add a recipient
    $mail->addAddress(‘[email protected]’);               // Name is optional
    $mail->addCC(‘[email protected]’);
    $mail->addBCC(‘[email protected]’);
    $mail->WordWrap = 50;                                 // Set word wrap to 50 characters
    //$mail->addAttachment(‘/usr/labnol/file.doc’);         // Add attachments
    //$mail->addAttachment(‘/images/image.jpg’, ‘new.jpg’); // Optional name
    $mail->isHTML(true);                                  // Set email format to HTML
     
    $mail->Subject = ‘Here is the subject’;
    $mail->Body    = ‘This is the HTML message body <b>in bold!</b>’;
    $mail->AltBody = ‘This is the body in plain text for non-HTML mail clients’;
     
    //Read an HTML message body from an external file, convert referenced images to embedded,
    //convert HTML into a basic plain-text alternative body
    //$mail->msgHTML(file_get_contents(‘contents.html’), dirname(__FILE__));
     
    if(!$mail->send()) {
       echo ‘Message could not be sent.’;
       echo ‘Mailer Error: ‘ . $mail->ErrorInfo;
       exit;
    }
     
    echo ‘Message has been sent’;
     

    if some one had solution about this, plez contact me on my email id,…[email protected]

  76. HI,

    Thank You for your quick response. I tried the code at the top of this page and it appears to work but no email shows up at my gmail email. Here is the link to my page https://ecbiz172.inmotionhosting.com/~efabri6/contact2.php

     

    I copied and pasted the code and inserted my email, any ideas what I might need to change.

     

    <?php

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

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

      

      //Email information

      $admin_email = “[email protected]”;

      $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” /><br />

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

      Message:<br />

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

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

      </form>

      

    <?php

      

      }

    ?>

     

     

    1. Hello Karen,

      Based on your account I was able to take a quick look at your email logs and I could see that the email was working. I then briefly tested the code myself with my own email address and it also worked. I had it send to my Gmail account and I received messages. You might be forwarding your messages somewhere else, or there’s a filter that’s removing messages – you will need to check to make sure that a spam filter or something else is not in the way. I hope this helps to let you know that the function is working.

      If you have any further questions or comments, please let us know.

      Regards,
      Arnel C.

  77. HI,

    I am new to coding and would like some advice on the easiet and simplest way to set up a contact form page. I was thinking of using a webtemplate and my gmail to recieve the contact info. The webplate does not include any php help. I use microsoft webexpression for editing. Can you recommend a simple article to follow in a step by step. The more I read the more complex this is looking. Thank You in Advance for any guidance you can give me!

    1. Hello Karen,

      You would just need to go to page -> Code and you would insert the code from this page. You would need to change the admin email address to your gmail.com account so the form knows where to send the emails to.

      Best Regards,
      TJ Edens

  78. I wanted my email to be send as HTML format and this is the code. The recieved email is a text with html tags.

    // if no errors send email

    if(!isset($error_message)) {

    // Header

    $headers = “From: ” . strip_tags($_POST[’email_address’]) . “\r\n”;

    $headers .= “Reply-To: “. strip_tags($_POST[’email_address’]) . “\r\n”;

    $headers .= “MIME-Version: 1.0\r\n”;

    $headers .= “Content-Type: text/html; charset=ISO-8859-1\r\n”;

     

    // Email

    $email_msg   = ‘<html><body>’;

    $email_msg  .= “<a href=\”https://” . $URL . “/\”>” . “<img src=https://” . $URL . “/images/logo.png  ” . “width=\”219\” height=\”71\”></a>”;

    $email_msg  .= “<p>Email was sent from: ” . $URL . “</p>”;

    .

    .

    .

    $email_msg  .= “</table></body></html>”;

     

    $mailTo = $mailTo;

     

    //send email

    mail($mailTo, $subject, $email_msg, “From:” . $email_address);

     

    if i added $headers to my mail line it will not work 

    mail($mailTo, $subject, $email_msg, $headers);

     

    Please advice

    Thanks

    1. Hello Mohammad,

      Unfortunately, we can’t really provide coding support. However, we do try to point you in the right direction. Check out this Sending Nice HTML email with PHP. This post provides information that you could use to send email as HTML using the PHP mail function.

      I hope this helps to answer your question, please let us know if you require any further assistance.

      Regards,
      Arnel C.

  79. alter the line mail($admin_email, “$subject”, $comment, “From:” . $email);
    to

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

    it will work.

  80. Sir Scott….Hmmm, thats fine Sir……one thing more….Can I add multiple headers more than we use in routine? How?

     

    1. Hello Muhammad,

      You could simply add a variable named headers and then add as many as you need. For instance:

      $headers = ‘From: [email protected]’ . “\r\n” .
      ‘Reply-To: [email protected]’ . “\r\n”

      You then insert that variable as one of the parameters in the mail() function.

      Kindest Regards,
      Scott M

  81. please am facing the challenge in using php to send mail. this is my code

    <?php 

     error_reporting(0);

     

     $to = $_REQUEST[‘sendto’] ; 

     $from = $_REQUEST[‘Email’] ; 

     $name = $_REQUEST[‘Name’] ; 

     $headers = “From: $from”; 

     $subject = “Web Contact Data”; 

     

     $fields = array(); 

     $fields{“Name”} = “Name”; 

     $fields{“Company”} = “Company”; 

     $fields{“Email”} = “Email”; 

     $fields{“Phone”} = “Phone”; 

     $fields{“list”} = “Mailing List”; 

     $fields{“Message”} = “Message”; 

     

     $body = “We have received the following information:\n\n”; foreach($fields as $a => $b){ $body .= sprintf(“%20s: %s\n”,$b,$_REQUEST[$a]); } 

     

     $headers2 = “From: [email protected]”; 

     $subject2 = “Thank you for contacting us”; 

     $autoreply = “Thank you for contacting us. Somebody will get back to you as soon as possible, usualy within 48 hours. If you have any more questions, please consult our website at www.oursite.com”;

     

     if($from == ”) {print “You have not entered an email, please go back and try again”;} 

     else { 

     if($name == ”) {print “You have not entered a name, please go back and try again”;} 

     else { 

       $send = mail(‘[email protected]’, $subject, $message, $headers); 

       mail($to, $subject, $body, $headers); 

    $send2 = mail($from, $subject2, $autoreply, $headers2); 

     if($send) 

     {header( “Location:localhost/thankyou.html” );} 

     else 

     {print “We encountered an error sending your mail, please notify [email protected]”; } 

     }

    }

     ?> 

     
  82. Hello!

    please help me i want to send mail to group, thats i maintain in database(email addresses)

    1. Hello Muhammad,

      You can either add more email addresses to the To section or create a forwarder on the receiving email that sends to the other desired email addresses.

      Kindest Regards,
      Scott M

    1. Hello vandana,

      Thank you for your question. I found a post via online search, where they are discussing possible ways to embed a link in php mail function. This may be a good starting point in determining how to code this.

      Thank you,
      John-Paul

  83. hi,

    what the conclusion of above disscussion…………..??????

    plz tell me exact solution that what changes should i make in php.ini and sendmail.ini file to sending rhe mail to user(that he should recive the mail).

    The output is only the messge.how should i know that mail is deliverd to the user???

    i dont want to use phpmailer() function.

    thanks

    1. Hello Purva,

      Apologies, but I’m not sure what you’re asking. The comments in this section are FOR using the php mail function. If you don’t want to use it, then you need to be using something else and your comment should be in an article appropriate to your topic. Changes in the php.ini and sendmail.ini files will NOT send email to a user. You will need to have some code that will do that. There built-in functions (such as phpmail and mail) in PHP that can be coded for that purpose, but we do not provide code beyond what we have provided in the articles written within the Support Center. If you want a tutorial on how to use phpmail, please see phpmail function.

      Kindest regards,
      Arnel C.

  84. Hi. This code doesn’t work for me either. Would be great if there was something like this that addressed my and other people’s issues. Some clear instructions for newbies would be much appreciated. Back to googling for simple form guidance…

    1. Hello Guy,

      Are you getting any particular error messages? If so, paste them here and we will be glad to take a look for you.

      Kindest Regards,
      Scott M

  85. my not receiving any mail,can you please let me know thw mistake

    <tr><td><input type=”submit” img src=”../images/1.png”  name=”add_main” value=”ADD”/>  </td></tr>

    <?php

    if($_POST[‘add_main’]){

    $from    =’[email protected]’;

    $to      = ‘[email protected]’;

    $subject = ‘test’;

    $message = ‘test completed’;

    $headers = ‘From: [email protected]’ . “\r\n” ;

    mail( $from, $to, $subject, $message, $headers);

    echo”sent”;

     

    }

    ?>

    1. Hello Romeo,

      You will want to place code around the mail function to test any error codes that it may be throwing.

      Kindest Regards,
      Scott M

    2. Hello Mav,

      Have you gotten any error messages? Have you tried echoing out the variables to be sure they are all correct? Have you tried any error trapping on the mail function to see if it is throwing any other error types?

      Kindest Regards,
      Scott M

  86. I dont reveieve any error messages, Email is working on other domains. I have a domain of [email protected] and [email protected], I was able to get the email using the travelats.ae but not the .com. And I have not made any changes on the DNS server.

    here is my code

     

    $order=$_POST[“order”];

    $amount=$_POST[“amount”];

    $bank=$_POST[“bank”];

    $mail=$_POST[“email”];

    $sender = “ATS Travel <[email protected]>”;

     

     

    // multiple recipients

    $to  = $mail;

    // subject

    $subject = ‘Payment Receipt’;

     

    // message

     

      $body = <<<EOD

    <br><hr><br>

    Your transaction is succesful! <br>

    Order: $order <br>

    Amount: $amount<br>

    Bank Reference Number: $bank<br>

    EOD;

    $headers .= “From: $sender\r\n”;

    $headers .= ‘MIME-Version: 1.0’ . “\r\n”;

    $headers .= ‘Content-type: text/html; charset=iso-8859-1’ . “\r\n”;

    $success = mail($to, $subject, $body, $headers);

    $theResults = <<<EOD

    EOD;

     

    echo “$theResults”;

     

    ;

    Thanks,

     

    Romeo 

  87. I have a problem about my mail function, Its working on all other domains but not working on our domain. we have a .ae domain that is working(I can recieve emails from them) but the .com is not (we are using Gmail as our hosting provider).

     

    Thanks in advance

     

    1. Hello Romeo,

      Thank you for your question. We are happy to help, but will need some additional information. What happens when you try to send the emails?

      Are you getting any errors? What are they?

      What is the .com domain? Have you confirmed the MX records are pointed to Gmail correctly?

      Have you made any DNS changes to the .com domain in the last 24 hours?

      Thank you,
      John-Paul

  88. PHP must be configured correctly in the php.ini file with the details of how your system sends email. Open php.ini file available in /etc/ directory and find the section headed [mail function].

    Windows users should ensure that two directives are supplied. The first is called SMTP that defines your email server address. The second is called sendmail_from which defines your own email address.

    The configuration for Windows should look something like this:

    [mail function]
    ; For Win32 only.
    SMTP = smtp.secureserver.net
    
    ; For win32 only
    sendmail_from = [email protected]
    

    Linux users simply need to let PHP know the location of their sendmail application. The path and any desired switches should be specified to the sendmail_path directive.

    The configuration for Linux should look something like this:

    [mail function]
    ; For Win32 only.
    SMTP = 
    
    ; For win32 only
    sendmail_from = 
    
    ; For Unix only
    sendmail_path = /usr/sbin/sendmail -t -i
    

     

    make the required modification in the php.ini file and try once again.

    1. Hello Kevin,

      Thanks for the question. There is not anything saying that you can’t have two admins, so you’re welcome to try it. If you want to be sure that the email makes it to BOTH email admins, then set up a forwarder for the administrator email address so that it forwards to your second administrator email address.

      Regards,
      Arnel C.

  89. <?php
    if(isset($_POST[‘submit’])){
        $to = “[email protected]”; // this is your Email address
        $from = $_POST[‘txtemail’]; // this is the sender’s Email address
        $name = $_POST[‘txtname’];
        $email = $_POST[‘txtemail’];
        $number = $_POST[‘txtphone’];
        $city = $_POST[‘txtcity’];
        $subject = “User Information”;
        //$subject2 = “Copy of your form submission”;
        $message = $name . ” ” . $email . ” ” . $number .” “. $city ;
        //$message2 = “Here is a copy of your message ” . $first_name . “\n\n” . $_POST[‘message’];
        $headers = “”
        $headers = “From:” . $from;
        //$headers2 = “From:” . $to;
        mail($to,$subject,$message,$headers);
        //mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
        echo “Mail Sent. Thank you ” . $first_name . “, we will contact you shortly.”;
        // You can also use header(‘Location: thank_you.php’); to redirect to another page.
        }
    ?>

     

    Dear sir,

                  i am working on this code and it is not working . i want send the information filled by the user to our mail but this code doing nothing please suggesed me .

    1. Hello Harshak,

      Unfortunately this snippet of code will not be helpful in fully troubleshooting the issue. What troubleshooting steps have you tried? Are you getting an error message? Are you able to echo out your specific variables to ensure they are being filled?

      Kindest Regards,
      Scott M

    2. Hello Anant,

      While we are happy to provide assistance, we do not provide coded solutions upon request. With the article above plus the information provided in the support center, you should be able to put together a form in the format you desire.

      Kindest Regards,
      Scott M

  90. Thanks for your kindly reply.

    Next, you are requested to provide the complete code at one place with facility of CC and BCC email and CAPTCHA protection.

     

    Thanks and regards,

    Anant

    1. Hello Anant,

      To add CC and BCC you need to include those as part of your headers. Replace the ‘From’ section with a $headers variable. Prior to calling that, you need to add the header content. It will look like something below:

      $headers = “From: [email protected]\r\n” .
      “X-Mailer: php\r\n”;
      $headers .= “MIME-Version: 1.0\r\n”;
      $headers .= “Content-Type: text/html; charset=ISO-8859-1\r\n”;
      $headers .= “CC: [email protected]\r\n”;
      $headers .= “Bcc: [email protected]\r\n”;

      This should assist you. Note that this is a sample and has not been tested, further modification may be required.

      Kindest Regards,
      Scott M

  91. Hi,  

    I have the same problem. I am using the PHPmail script. I config this script and it shows the message “Mail has been sent”. But didnt reached at desired email location. Please Anyone helps me to solve this issue.

    1. Hello Arvinder,

      If you are working with the phpmail function and got the “Mail has been sent” message, it should have been sent from the server. You will now need to check the server logs and see if the message was indeed sent and if it was received properly by the other server.

      Kindest Regards,
      Scott M

  92. I am use your phpmail function ok, function is work fine & mail send & receive ok,

    when i am add my more input box main name input box then create a problem.

    <?php
    //if “email” variable is filled out, send email
      if (isset($_REQUEST[’email’]))  {
     
      //Email information
      $admin_email = “[email protected]”;
      $name = $_REQUEST[‘name’];
      $company = $_REQUEST[‘comname’];
      $email = $_REQUEST[’email’];
      $subject = $_REQUEST[‘subject’];
      $comment = $_REQUEST[‘comment’];
     
      //send email
      mail($admin_email,$name,$company,$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”>
      Name: <input name=”name” type=”text” /><br />
      Company: <input name=”comname” type=”text” /><br />
      Email: <input name=”email” type=”text” /><br />
      Subject: <input name=”subject” type=”text” /><br />
      Message:<br />
      <textarea name=”comment” rows=”15″ cols=”40″></textarea><br />
      <input type=”submit” value=”Submit” />
      </form>
     
    <?php
      }
    ?>

    Problem::Warning: mail() expects at most 5 parameters, 6 given in /home/mailsend.php on line 22

     

    how to solve it.

    1. Hello Nayeem,

      The php mail() function needs at least 3 arguments, and has two optional ones, totaling 3-5 arguments. These arguments are specific arguments and not ones you can create on your own. The required arguments are ‘to’, ‘subject’, and ‘message’ with the optional ones being ‘additional headers’ and ‘additional parameters’.

      Your call to the function has some different arguments and totals 6, so you will need to fit those custom arguments into your message and then reformat the function call to match the standard php mail() function call.

      You can learn more about that function here at thephp manual page.

      Kindest Regards,
      Scott M

  93. Hello Iam Alaa i have error and i can not find it can help me when i sent to email see this massage what can i do

    Deprecated: Function eregi() is deprecated in C:\wamp\www\Light\js\sendmail.php on line 49

     

     

    1. This means that you are using a function that has been removed from newer versions of PHP within that code located at C:\wamp\www\Light\js\sendmail.php. You will need to further investigate the code of that file and re-write the PHP to allow it to work on newer versions of PHP.

    2. when use this code this error ocur(” Warning: mail(): Failed to connect to mailserver at "localhost" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()”) and we can not handle this :O

  94. this code is selecting an email address from my database and is going to send a message to the selected email. the code works fine but not the mail function for $to = $address

    $to = $address;

    (mail($to,$subject,$txt,$headers);

     

     

    // select statement
            $SQLString = “SELECT email\n”
            . “FROM tutor\n”
            . “WHERE MATCH(text_data) AGAINST (‘{$messageText}’ IN BOOLEAN MODE)\n”
            . “GROUP BY id\n”
            . “ORDER BY sum(5) DESC”;
       
    echo $SQLString; 

            $result = mysql_query($SQLString);

            // Verify it worked
            if (!$result) echo mysql_error();

            // execute select statement
            $row = mysql_fetch_row($result);

            // Should show you an integer result.
            $address = print_r($row, true);
           
    echo $address;
           
            $to = $address;
            $subject = “testing…”;
            $txt = $messageText;
            $headers = $senderPhone;
           
            if (mail($to,$subject,$txt,$headers))
            {
            echo “successful”;
            }
            else
            {
            echo “error”;
            }

     

    thanks for any help in advance 🙂

    1. Hello Kaleb,

      From the way you phrased your question, it seems that you are having issues with $to taking the value of $address. The code snippet you provided does not show where the $address variable is filled. What do you get when you echo $address? The $to = $address is not a function, but an assignment, making $to the value of whatever is in $address at the time. Do the other variables ($subject, $txt, etc) receive their values?

      The mail($to,$subject,$txt,$headers) function is called but you do not have any code to catch and display the return code to know why it is failing. You will need to do that in order to understand what is going on.

      Kindest Regards,
      Scott M

  95. I use LAMP postfix centos and this script :)) i recive Thank you for contacting us! but i dont recive the mail please help me

    1. Hello,

      You will need to check in your email logs to see if the email went out or if there is an error message.

      Kindest Regards,
      Scott M

  96. following code is not working

    —————————————————–

     

    <?php
        $to = ‘[email protected]’;
       
        $subject = ‘Website Change Reqest’;
       
        $message=”Message Goes Here”;

        $headers = “MIME-Version: 1.0\r\n”;
        $headers .= “Content-Type: text/html; charset=ISO-8859-1\r\n”;

        if (mail($to, $subject, $message, $headers))
        {
          echo ‘Your message has been sent.’;
        }
       
        else
        {
          echo ‘There was a problem sending the email.’;
        }
    ?>

    1. Hello Satbir,

      Are you getting an error message? If so, what is it? Where are you trying to use this code? Is it a webserver or a WAMP, XAMP, LAMP setup?

      Kindest Regards,
      Scott M

  97. Hi,

    Thank you for the speedy reply.

    I have made changes to the PHP code and now have the message come through in the body of the mail but still cannot get the visitors email to come up as FROM:…. just comes from my webhost name. see code below:

    <?php

    //if “email” variable is filled out, send email
      if (isset($_POST [‘submit’] ))  {
     
      //Email information
      $to = “[email protected]”;
      $from = ’email’;
      $name = $_POST[‘name’];
      $email = $_POST[’email’];
      $message = $_POST[‘message’];
     
      //send email
      mail($to,$email, $name, $message,$from);
     
      //Email response
      echo “Thank you for contacting us! We will contact you shortly “;
      } 
    ?>

    1. Hello Mo,

      If you look closely at your code, take a close at your $from. I think that’s the problem. Make sure you’re using the right variable there and then everything should be okay.

      I hope that helps!

      Regards,
      Arnel C.

    2. Hello Chike,

      While your question is about email, it does not relate to this article directly. I have moved your question to be a brand new question. You can find it here.

      Kindest Regards,
      Scott M

    3. Hello priya,

      Thank you for your suggestion. For anyone else who may find this post, here is a helpful link to the w3Schools page on PHP 5 mail() Function.

      Thank you,
      John-Paul

  98. Hi there, i have made use of the basic PHP mail code thanks to you but the issue im having is that the email comes through to me from my hosting server and no comments added to the email… subject is the visitors email address as i set it… see below and please advise if i am doing it wrong:

    <?php
    //if “email” variable is filled out, send email
      if (isset($_REQUEST[’email’]))  {
     
      //Email information
      $to = “[email protected]”;
      $name = $_REQUEST[‘name’];
      $email = $_REQUEST[’email’];
      $telephone = $_REQUEST[‘telephone’];
      $comments = $_REQUEST[‘comments’];
     
      //send email
      mail($to,$name,$comments);
     
      //Email response
      echo “Thank you for contacting us!”;
      }
      
     
    ?>

    1. Hello Mo,

      Make sure that you when you use the code above, that it’s spaced out with the comments on their own line – like the following:

      
      

      Your email form requires should be asking for the comment as well. As per the code above, the form section has “comment” set in the text area. I hope that helps to clarify the issue! Please let us know if you have any further questions.

      Regards,
      Arnel C.

  99. Q .As u ve mentioned here

    $admin_email = "[email protected]";

    to send mail to that particular mail address.. I m using phpmailer n its working fine for me to send mail to any gmail or yahoo mail but not to any custom mail address.

    I want to send mail to any custom domain address by phpmailer. Any help here  ??

    1. Hello Pooja,

      If the you are successfully sending emails to some addresses but not others, then the issue would not likely be with the function. You will want to test by sending an email from your server via webmail to the address that is not receiving it. Look for a return message in that email account for the reason why it is not getting through.

      Kindest Regards,
      Scott M

  100. 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\design\mail.php on line 13

    what will i do now

    1. Hello Antara,

      When you use ‘localhost’ in your settings, that means it will look on the current computer. If you are using this on your local computer, yuo likely do not have it set up as a mail server, which is why you are getting the message. You will need to have it point to a server with mail serving functionality, such as your webhosting server.

      Kindest Regards,
      Scott M

  101. hi, i want to create auto responder and get the data into database and its like send a data differently to sender. help me

    how could i create it. im very new in php

    1. Hello Eihton,

      While not a difficult task, it would require a few more pieces to be added. To auto respond to the customer, you would need to add another piece of code that emails out that the information was received. Then, to add the data to the database you would need to have the proper tables set up in an existing database, code for php to connect to the database, then build your SQL query using the information input by the user as the data to insert. Finally you would insert that data into the database.

      Unfortunately we currently do not have that type of tutorial information available, however there are many articles and tutorials around the web for each part that is required. I have given you the layout, so go from there and see if you can find code samples to assist. Be sure to also read up on error checking and avoiding SQL injection from malicious users to protect your database.

      Kindest Regards,
      Scott M

  102. i’m new in programming, i created a form to send email from my website to yahoomail but i got this error

    Failed to connect to mailserver at “localhost” port 25, verify your “SMTP” and “smtp_port” setting in php.ini or use ini_set()

    what can i do

    1. Hello Morphy,

      As your PHP error states, it can’t connect to the server localhost on port 25.

      You’ll need to check with your web host to find out what mail server you should be using. You might need to send mail with phpMailer instead of the default PHP mail() function depending on your server configuration.

      You more than likely need to define some SMTP settings, and use the same server and account information you would use when setting up a normal email account on your desktop. Or your web host might let you know you need to define another SMTP port rather than 25 in your php.ini file.

      – Jacob

  103. I am using WordPress WooCommerce and my order confirmation emails are not being sent. I am using an email forward to send mail ([email protected] forwards to an AOL email account). Would this prevent emails from being sent if I am using the default DNS records? I also have not changed the Email Routing option to Remote Mail Exchanger.

    1. Hello Fawn,

      I would recommend sending your order confirmations directly to an email account hosted on the same domain as your WordPress site to rule out any 3rd party delivery errors.

      If you are missing any order confirmations at your AOL.com address I would suggest that you login to webmail and check for them locally on the server.

      I do see some delivery errors from your account to AOL.com and this will happen from time to time, as AOL offers free email accounts and sometimes will reject automated messages from servers, especially on their first delivery attempts. This is also referred to as temporary defferment and is mentioned on this AOL page about 421 errors which is what some of your mails are getting rejected by.

      Please let us know if you had any further questions.

      – Jacob

  104. on my own system here, if i view my mail send has a text, i saw everything.

    But on other peoples laptop, they saw the message and the link but inside the link all the field i call from mysql server to that notification page was not showing.

    1. Hello Olorunnisola,

      Thank you for contacting us today. Since you are having trouble coding a PHP contact form, I recommend following our updated guide on How to create a custom PHP contact form with validation.

      That tutorial provides a successful example that should help you code your form.

      If you have any further questions, feel free to post them below.
      Thank you,

      -John-Paul

  105. Thank you scott, 

    here are my codes:

        //var_dump($link);

    //$msg = wordwrap($msg,70);

       $subject = “Call For Meeting”;

       $message = “Dear”.” “.”Sir\Madam,”.

    “You had been invited to attend a meeting by the name organization”.” “.$org_ind.” “.”that is to hold on”.” “.$date.” “.”by”.” “.$start_time.” “.”via online, Based on”.” “.$meeting_title.”.”.”Your feedback about this proposed meeting will be of better help for the preparation.

    Please click to give your view.”.” “.”<a href=’https://exolvetechnologies.com/meeting/Notification.php?call_for_meeting.php = $meetingId’>Notification</a>”.” “.”Thank you.<br>”;

    // Always set content-type when sending HTML email

    $headers = ‘MIME-Version: 1.0’. “\r\n”;

    $headers .= ‘Content-type:text/html;charset=UTF-8’. “\r\n”;

    $headers .= ‘From: Gentlesoul <[email protected]>’. “\r\n”;

       foreach($_POST[‘division_name’] as $key =>$email)

      {

          $mail = mail($email,$subject,$message,$headers);

          //var_dump($email);

            if ($mail) {

          echo “<p>Message sent!</p>”;

         } else {

           echo “<p>Message delivery failed…</p>”;

         }

      }

    The project is my own personal project that i want to host by tuesday, please help me.

    have not being here before, this will be my first time.

    About the text format! I mean to give client opportunity to bold,italic or number list to typing text has he or she type.

     

     

       echo “<h4>Meeting set successful!</h4>”;

    }

  106. Please someone teach me how to create ds text formats and attached files form computer to a textarea on a webpage.

    1. Hello Olorunnisola,

      We are unfamiliar with what you mean by ds text format. Could you be more specific in what you are trying to accomplish?

      Kindest Regards,
      Scott M

    2. Hello Olorunnisola,

      If you are not getting any errors or messages saying the email was not sent, but the recipient is not able to see the email, you will want to contact our Live Support team to see if they can confirm the email actually left the server. If it did, then the script worked properly and the issue maybe on the receiving end. If not, they may be able to see something specific to advise you on a next step.

      Kindest Regards,
      Scott M

  107. Please, i am sending email via phpmail() with a link, the link work perfectly but did not display any information posted to the link from sql. And even the email is not  entering into inbox of my client.

    can you help me? 

  108. Just wanted to mention an issue I just ran across in the hopes that it might help someone else.  In our situation we use inmotion for web hosting, but host email for the same domain locally in our network. When the domain was set up on inmotion, thedefault setting was to use InMotion’s MX server, so all email sent to address on our domain were attempted delivery to inmotion rather than our mail server.  I think I’ve fixed this by setting the mx servers to be remote instead of local.

    1. Hello Nathan, and thanks for the comment!

      Yes you are correct that if your domain’s email is not hosted with us, when you try to deliver from a PHP script it will try to deliver it locally unless you change DNS records to have email hosted by a 3rd party.

      You also need to set the Email Routing option to Remote Mail Exchanger instead of the local one like you mentioned.

      Thanks again for your comment!

      – Jacob

  109. mail is not send to the correspomding mail address.. pls give any suggestions…and i m a new devoloper to php socan u sugest me how to use

     phpMailer script…

     

  110. Hi Jacob, 

     i was alredy used the phpmailer code it was shown the error of Message was not sent.Mailer error: SMTP connect() failed.. 

    1. Hello Sankar,

      If you’re getting a SMTP connect() failed error, then this means your PHP script can’t establish a SMTP connection with the server you’ve entered into your script.

      Are you possibly trying to connect to a secure mail server by chance? You might need some additional settings in your phpMailer script such as:

      $mail->SMTPSecure = 'tls';
      $mail->Host = "secure.example.com";

      If you’re still having issues let us know.

      – Jacob

  111. Hi , 

    This code is working properly and display ed the msg as Thank you for contacting us but mail is not send to the correspomding mail address.. pls give any suggestions…

    1. Hello Sankar,

      It’s possible that the message is ending up in a spam folder in the recipient’s email address due to the mail coming directly from a PHP script.

      If that is the case, you could use something like phpMailer in order to send an SMTP authenticated email.

      Either that or there is some incorrect information typed in to your script. The Thank you for contacting us! message is displayed if the email form is submitted, but it doesn’t actually check to ensure that the mail was delivered. If you have access to the server’s mail logs, you should be able to see if the PHP mail attempt is making it to the local server to even attempt a delivery out.

      It looks like we might need to update the example script used in this guide to at least wrap the code with if (!mail( …)){ echo “Failure” } code to see if the server accepts the PHP mail attempt. However this is more just a proof of concept then something you’d probably want to use on a live contact form for your website.

      – Jacob

Was this article helpful? Join the conversation!

Server Madness Sale
Score Big with Savings up to 99% Off

X