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

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

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

Basic PHP email() function code

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

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

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

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

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

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

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

  • Greetings self/master coders all over!

    My  issue is… 

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

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

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

     

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

    but it show error

     

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

    <?php

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

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

      

      //Email information

      $admin_email = “mygangkrish@gmail.com”;

      $email = $_REQUEST[’email’];

      $subject = $_REQUEST[‘subject’];

      $comment = $_REQUEST[‘comment’];

      

      //send email

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

      

      //Email response

      echo “Thank you for contacting us!”;

      }

      

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

      else  {

    ?>

     

     <form method=”post”>

     

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

     

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

     

      Message:

     

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

     

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

      </form>

      

    <?php

      }

    ?>

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

  • This is my site

    mnjewellers.com

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

     

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

     

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

     

    Can you help me out of this.

     

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

  • How to run PHP code in background ?

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

    pls ans me.

     

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

  • how to fix error ? 

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

  • this Error Show 

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    </form>

     

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

  • This code working fine on my web site.

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

    thanking for your error free code

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

  • Sir thanx for the code..

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

     

  • Sir,

    Thank you for a code.

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

     

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

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

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

  • 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? 

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

  • 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?

    • 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

  • I am having trouble with my form

    <?php

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

     

        // EDIT THE 2 LINES BELOW AS REQUIRED

        $email_to = “edutanui@gmail.com”; 

        $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=http://test.rafikiweb.com/thanks.html\”>”; //Add a thankyou page with a Close button.

    ?>

     

    <?php

    }

    ?>

     

     

     

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

  • 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 “xxxx@xxx.com” in place of $email.  Any thoughs? Thanks!

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

  • 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

    • 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

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

  • 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

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

    • 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 “example@domain.in” 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.

    • 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****biz166@inmotionhosting.com not with my domain eamil address ****@ssfhl.com. Is there a way to change that?

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

    • 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

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

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

  • sir,

    I use this code for email sending but it’s not working in my program.

    i get this type of error

     


    Warning: mail() [function.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 C:\wamp\www\mail\mail.php on line 12
    Thank you for contacting us!

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

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

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

     

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

  • 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 test@test.com, 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 : wordpress@mysiteurl.domainname

    My question is how to get the sender email instead ?
    How to get your email, the email that you entered in the input field : test@test.com ?

    Thanks again

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

  • 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

    • LebCit, I would try adding the following code in your PHP file after your line that says “$headers = $_POST[’email’];”

      $from = "sendingEmailAddress@yourDomainOfChoice.com";
      $headers .= "From:  $from";
      $headers .= "Reply-to: noreply@mydomainname.com\r\n";
  • 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

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

  • 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!

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

     

     

  • 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 = ‘noreply@mycompany.com’;

    $mail->Password = ‘password’;

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

    $mail->Port       = 25;   

    $mail->SMTPDebug = 4;              

    $mail->From = $email;

    $mail->FromName = $name;

    $mail->addAddress($to, ‘Enquiry’);$mail->AddCC(‘pj.itexpert@gmail.com ‘, ‘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>

    • 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

  • 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 = “dashmonalisa969@gmail.com”;

      $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    = “130301csl063@cutm.ac.in”;  

                $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”] = “130301csl063@cutm.ac.in”;  

                $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

      }

    ?>

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

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

  • 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?

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

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

  • 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?

  • 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 = “info@madecor.com”;

     

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

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

  • 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!

    • 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

  • 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 = “suresh.kumar@anantha.co.in”;

           $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  

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

  • 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

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

    • Hello aditya,

      Thank you for contacting us. You should replace “someone@example.com” 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

  • 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

    • Hello Siva,

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

      Best Regards,
      TJ Edens

  • 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

  • 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!

  • Hi Scott,

    Your header for Bcc is not working, it should be like this

    $headers .= "BCC: admin@example.com\r\n";

    but apart from that,its working fine!
    Thanks.
  • 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?

  • 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   = “techinnoexcel@gmail.com”;  // 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();
        }
    }
       

    ?>

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

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

    • 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

  • 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 =”support@medcoair.com”;

             $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

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

  • 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…

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

  • hello all…

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

     can anyone help me????? 

    #Scott #Arn plz help me…

  • 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?

    • 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

  • 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

     

     

     

     

     

     

     

     

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

  • 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?

    • Hello LG,

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

      Kindest Regards,
      Scott M

  • 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: http://akhil.xyz

    Thanks.

    Akhil K A

  • 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 = ‘recepient@yourdomain.com’;
    $Subject = ‘Send Email’;
    $Message = ‘i want to send the logis details here  example email:hshshshs password: xxxxx ‘;
    $Headers = “From: sender@yourdomain.com \r\n” .
    “Reply-To: sender@yourdomain.com \r\n” .
    “Content-type: text/html; charset=UTF-8 \r\n”;
     
    mail($To, $Subject, $Message, $Headers);
    ?>

    please help as soon as possible

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

    • 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

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

    <?php

         $email_to = ‘info@khawabnama.com’;

    $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: http://www.khawabnama.com/index.php‘);

        //die; 

     

     

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

    • 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

  • 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 .= “realconcept@usa.com”;

    $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 <mike@guardreports.co.za>’ . “\r\n”;//<noreply@example.com>’

     

    $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(‘realconcept@usa.com’, $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?

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

  • showing this error

     mail() [function.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 C:\xampp\htdocs\chi\PHP_Mail_function_Contact_US.php on line 105
    Thank you for contacting us!

    • 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

  • 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(“admin@nfotech.com”, ” Contact Form : “, $comments, “From: $email”))
             {
             echo ‘<script type=”text/javascript”>alert(“Mail sent”); </script>’;
             }
             else { echo ‘<script type=”text/javascript”>alert(“Not sent”); </script>’; }
              }
    ?>

    • 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

  • 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

    • 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

  • 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

    • 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

  • <?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 =”sejalsmruti@gmail.com”;

    $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 

    • 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

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

  • 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 ?

    • 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

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

  • hello,

     

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

  • 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 = “anton_paraggua@yahoo.com”;

      $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

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

  • Sir,

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

     $to = “someone@example.com”;

      $subject = “ABCD”;

      $comment = “Abcdefgh”;

      $header = “From:das.dhananjay@gmail.com \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.

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

    • 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

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

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

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

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

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

      Kindest Regards,
      Scott M

  • 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

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

  • 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 

    • 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

  •  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

     

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

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

  • 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 = ‘anything@gmail.com’;                   // 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(‘anything@yahoo.com’);  //Set an alternative reply-to address
    $mail->addAddress(‘anything@yahoo.com’);  // Add a recipient
    $mail->addAddress(‘anything@yahoo.com’);               // Name is optional
    $mail->addCC(‘anything@yahoo.com’);
    $mail->addBCC(‘anything@yahoo.com’);
    $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,….vijaybhat1981@gmail.com

  • 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 http://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 = “nebraskaantiques@gmail.com”;

      $email = $_REQUEST[’email’];

      $subject = $_REQUEST[‘subject’];

      $comment = $_REQUEST[‘comment’];

      

      //send email

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

      

      //Email response

      echo “Thank you for contacting us!”;

      }

      

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

      else  {

    ?>

     

     <form method=”post”>

      Email: <input name=”email” type=”text” /><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

      

      }

    ?>

     

     

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

  • 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!

    • 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

  • 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=\”http://” . $URL . “/\”>” . “<img src=http://” . $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

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

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

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

    it will work.

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

     

    • Hello Muhammad,

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

      $headers = ‘From: webmaster@example.com‘ . “\r\n” .
      ‘Reply-To: webmaster@example.com‘ . “\r\n”

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

      Kindest Regards,
      Scott M

  • 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: noreply@YourCompany.com“; 

     $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 http://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(‘user@example.com’, $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 webmaster@YourCompany.com“; } 

     }

    }

     ?> 

     
    • 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

    • 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

  • 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

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

  • 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…

    • 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

  • 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    =’xyz@gmail.com’;

    $to      = ‘rt@gmail.com’;

    $subject = ‘test’;

    $message = ‘test completed’;

    $headers = ‘From: supernona151992@gmail.com‘ . “\r\n” ;

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

    echo”sent”;

     

    }

    ?>

    • 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

    • 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

  • I dont reveieve any error messages, Email is working on other domains. I have a domain of romeo@travelats.com and romeo@travelats.ae, 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 <info@travelats.com>”;

     

     

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

  • 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

     

    • 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

  • 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 = xyz@yourdomain.com
    

    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.

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

  • <?php
    if(isset($_POST[‘submit’])){
        $to = “Harshakratn@gmail.com”; // 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 .

    • 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

    • 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

  • 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

    • 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: no-reply@example.com\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: admin@example.com\r\n”;
      $headers .= “Bcc: admin@example.com\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

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

    • 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

  • 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 = “someone@gmail.com”;
      $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.

    • 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

  • 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

     

     

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

    • 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

  • 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 🙂

    • 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

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

    • 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

  • following code is not working

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

     

    <?php
        $to = ‘satbir4@gmail.com’;
       
        $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.’;
        }
    ?>

    • 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

  • 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 = “admin@squareonline.co.za”;
      $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 “;
      } 
    ?>

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

    • 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

  • 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 = “admin@mydomain.co.za”;
      $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!”;
      }
      
     
    ?>

    • 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:

      < ?php
      //if "email" variable is filled out, send email
      
        if (isset($_REQUEST['email']))  {
      
        //Email information  
        
        $to = "admin@mydomain.co.za";  
        $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!";  
        }    
        ?>
      

      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.

  • Q .As u ve mentioned here

    $admin_email = "someone@example.com";

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

    • 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

  • 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

    • 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

  • 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

    • 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

  • 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

    • 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

  • I am using WordPress WooCommerce and my order confirmation emails are not being sent. I am using an email forward to send mail (example@mydomain.com 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.

    • 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

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

  • 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=’http://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 <emmanuelabiodun2011@live.com>’. “\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>”;

    }

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

    • 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

    • 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

  • 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? 

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

    • 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

  • 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…

     

  • Hi Jacob, 

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

    • 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

  • 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…

    • 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

Leave a Reply to pavithra Cancel reply