1

My validation contact form is not working. While I try to submit the form the following error occurs:

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 E:\CMS_Site\wamp\www\sitename\contents\send_mail.php on line 53

<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('eWTy3pUA1Okb-4lwUtk4dg');
if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL  && isset($_POST['message']) != NULL )
{ // if(isset($_POST['submit_form']) != NULL) IF START
$name = strtoupper (trim($_POST['name']));
$address = trim($_POST['address']);
$email = strtolower(trim($_POST['email']));
$contact = trim($_POST['contact']);
$country = trim($_POST['country']);
$website = trim($_POST['website']);
$subject = trim($_POST['subject']);
$message = trim($_POST['message']);
//---------------------------------------------
error_reporting(E_ALL ^ E_NOTICE);
$my_email = "kiranpahadi@gmail.com";
$errors = array();
// Remove $_COOKIE elements from $_REQUEST.
if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
// Validate email field.
if(isset($_REQUEST['email']) && !empty($_REQUEST['email']))
{
$_REQUEST['email'] = trim($_REQUEST['email']);
if(substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){$errors[] = "Email address is invalid";}else{$exploded_email = explode("@",$_REQUEST['email']);if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){$errors[] = "Email address is invalid";}else{if(substr_count($exploded_email[1],".") == 0){$errors[] = "Email address is invalid";}else{$exploded_domain = explode(".",$exploded_email[1]);if(in_array("",$exploded_domain)){$errors[] = "Email address is invalid";}else{foreach($exploded_domain as $value){if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){$errors[] = "Email address is invalid"; break;}}}}}}
}
// Check referrer is from same site.
if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){$errors[] = "You must enable referrer logging to use the form";}
// Check for a blank form.
function recursive_array_check_blank($element_value)
{
global $set;
if(!is_array($element_value)){if(!empty($element_value)){$set = 1;}}
else
{
foreach($element_value as $value){if($set){break;} recursive_array_check_blank($value);}
}
}
recursive_array_check_blank($_REQUEST);
if(!$set){$errors[] = "You cannot send a blank form";}
unset($set);
// Display any errors and exit if errors exist.
if(count($errors)){foreach($errors as $value){print "$value<br>";} exit;}
if(!defined("PHP_EOL")){define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");}
// Build message.
function build_message($request_input){if(!isset($message_output)){$message_output ="";}if(!is_array($request_input)){$message_output = $request_input;}else{foreach($request_input as $key => $value){if(!empty($value)){if(!is_numeric($key)){$message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;}else{$message_output .= build_message($value).", ";}}}}return rtrim($message_output,", ");}
$message = build_message($_REQUEST);
$message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
$message = stripslashes($message);
$subject = stripslashes($subject);
if($email)
{
$headers =  "From: {$name} <{$_REQUEST['email']}>";
$headers .= PHP_EOL;
$headers .= "Reply-To: " . $_REQUEST['email'];
}
else
{
if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){$from_name = stripslashes($_REQUEST['name']);}
$headers = "From: {$name} <{$_REQUEST['email']}>";
}
mail($my_email,$subject,$message,$headers);
?>
<b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
<?php
//---------------------------------------------
}
else
{
?>
<script type="text/javascript">
function validate_mail()
{
var mail_name=document.mail_form.name.value;
var mail_email=document.mail_form.email.value;
var mail_contact=document.mail_form.contact.value;
var mail_message=document.mail_form.message.value;
var mail_subject=document.mail_form.subject.value;
var spaceRegxp = /\w+/; 
var emailRegxp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
var contactRegxp = /^\d+$/;
if (spaceRegxp.test(mail_name) != true){

        alert("PLEASE CHECK NAME");
                    document.mail_form.name.focus();
                    return false;}
if (emailRegxp.test(mail_email) != true){

        alert("PLEASE CHECK EMAIL");
                    document.mail_form.email.focus();
                    return false;}                      
if (contactRegxp.test(mail_contact) != true){
        alert("PLEASE CHECK CONTACT NUMBER");
                    document.mail_form.contact.focus();
                    return false;}
if (spaceRegxp.test(mail_subject) != true){
        alert("PLEASE CHECK Subject");
                    document.mail_form.subject.focus();
                    return false;}
if (spaceRegxp.test(mail_message) != true){
        alert("PLEASE CHECK MESSAGE");
                    document.mail_form.message.focus();
                    return false;}
else {
document.mail_form.action = 'index.php?t=contact&i=25';
document.mail_form.btn_submit.disabled=1;
document.mail_form.btn_submit.value = '     PLEASE WAIT ...    ';
document.mail_form.submit();
}
}
</script>
<form name = "mail_form" method="post" enctype="multipart/form-data">
<div><label for="name"> Full Name: </label> <input name="name" type="text" size="50"  /> </div> 
<div><label for="address"> Address: </label> <input name="address" type="text" size="50"   /></div>
<div><label for="email"> Email:  </label><input name="email" type="text" size="50"   /></div>
<div><label for="contact">Contact:</label>  <input name="contact" type="text"  size="50"  /></div>
<div><label for="country">Country:</label> <input name="country" type="text"   size="50" /> </div>
<div><label for="website">Website:</label> <input name="website" type="text"   size="50" /> </div>
<div><label for="subject">Subject:</label> <input name="subject" type="text"   size="50" /> </div>
<div><label for="message">Your Message:</label> 
<textarea name="message" cols="40" rows="8"></textarea>
</div>
<div>    <p>      <input type="Button" name="btn_submit"  id="submit-go" value="     Send Mail     " onClick="validate_mail()"/>    </p>
</div>
</form>
<?php
}
?>
Jklyn
  • 352
  • 3
  • 19

2 Answers2

2

Your code for sending mail through php has no issue at all. if you are using WAMP in windows ,their will not have any SMTP server setup. so if you need to send mail from WAMP you need to use any SMTP server support.You can use Mandrill Mailchimb to send Email from localhost by just create an a/c in it, download swift files and add it in your working directory to setup mail server.To read-more on how to send mail through mandrill see below code..

or

You can work this code in a live server which supports SMTP setup.
Sending Mail via Mandrill Swift files in your code.You can change message subject etc as your own.

send_mail.php

    <?php
    if(isset($_POST['name']) != NULL && isset($_POST['email']) != NULL  && isset($_POST['message']) != NULL ){ 
        $name = strtoupper (trim($_POST['name']));
        $address = trim($_POST['address']);
        $email = strtolower(trim($_POST['email']));
        $contact = trim($_POST['contact']);
        $country = trim($_POST['country']);
        $website = trim($_POST['website']);
        $subject = trim($_POST['subject']);
        $message = trim($_POST['message']);
        //---------------------------------------------
        error_reporting(E_ALL ^ E_NOTICE);
        $my_email = "kiranpahadi@gmail.com";
        $errors = array();
        // Remove $_COOKIE elements from $_REQUEST.
        if(count($_COOKIE)){foreach(array_keys($_COOKIE) as $value){unset($_REQUEST[$value]);}}
        // Validate email field.
        if(isset($_REQUEST['email']) && !empty($_REQUEST['email'])){
            $_REQUEST['email'] = trim($_REQUEST['email']);
            if(substr_count($_REQUEST['email'],"@") != 1 || stristr($_REQUEST['email']," ") || stristr($_REQUEST['email'],"\\") || stristr($_REQUEST['email'],":")){
                $errors[] = "Email address is invalid";
            }
            else{
                $exploded_email = explode("@",$_REQUEST['email']);
                if(empty($exploded_email[0]) || strlen($exploded_email[0]) > 64 || empty($exploded_email[1])){
                    $errors[] = "Email address is invalid";
                }
                else{
                    if(substr_count($exploded_email[1],".") == 0){
                        $errors[] = "Email address is invalid";
                    }
                    else{
                        $exploded_domain = explode(".",$exploded_email[1]);
                        if(in_array("",$exploded_domain)){
                            $errors[] = "Email address is invalid";
                        }
                        else{
                            foreach($exploded_domain as $value){
                                if(strlen($value) > 63 || !preg_match('/^[a-z0-9-]+$/i',$value)){
                                    $errors[] = "Email address is invalid"; 
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }
        // Check referrer is from same site.
        if(!(isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']) && stristr($_SERVER['HTTP_REFERER'],$_SERVER['HTTP_HOST']))){
            $errors[] = "You must enable referrer logging to use the form";
        }
        // Check for a blank form.
        function recursive_array_check_blank($element_value){
            global $set;
            if(!is_array($element_value)){
                if(!empty($element_value)){
                    $set = 1;
                }
            }
            else{
                foreach($element_value as $value){
                    if($set){
                        break;
                    } 
                    recursive_array_check_blank($value);
                }
            }
        }
        recursive_array_check_blank($_REQUEST);
        if(!$set){
            $errors[] = "You cannot send a blank form";
        }
        unset($set);
        // Display any errors and exit if errors exist.
        if(count($errors)){
            foreach($errors as $value){
                print "$value<br>";
            }
            exit;
        }
        if(!defined("PHP_EOL")){
            define("PHP_EOL", strtoupper(substr(PHP_OS,0,3) == "WIN") ? "\r\n" : "\n");
        }
        // Build message.
        function build_message($request_input){
            if(!isset($message_output)){
                $message_output ="";
            }
            if(!is_array($request_input)){
                $message_output = $request_input;
            }
            else{
                foreach($request_input as $key => $value){
                    if(!empty($value)){
                        if(!is_numeric($key)){
                            $message_output .= str_replace("_"," ",ucfirst($key)).": ".build_message($value).PHP_EOL.PHP_EOL;
                        }
                        else{
                            $message_output .= build_message($value).", ";
                        }
                    }
                }
            }
            return rtrim($message_output,", ");
        }
        $message = build_message($_REQUEST);
        $message = $message . PHP_EOL.PHP_EOL."-- ".PHP_EOL."The Message has been submitted successfully ";
        $message = stripslashes($message);
        $subject = stripslashes($subject);
        if($email){
            $headers =  "From: {$name} <{$_REQUEST['email']}>";
            $headers .= PHP_EOL;
            $headers .= "Reply-To: " . $_REQUEST['email'];
        }
        else{
            if(isset($_REQUEST['name']) && !empty($_REQUEST['name'])){
                $from_name = stripslashes($_REQUEST['name']);
            }
            $headers = "From: {$name} <{$_REQUEST['email']}>";
        }
        include_once "swift/lib/swift_required.php";
        $from = array("frommail@mail.com" => "Your Name");
        $to="kiranpahadi@gmail.com";
        $message = "Hello  -This is a test mail";
        $subject = "Subject – Test";
        $transport = Swift_SmtpTransport::newInstance('smtp.mandrillapp.com', 587);
        $transport->setUsername('kiranpahadi@gmail.com');
        $transport->setPassword('eWTy3pUA1Okb-4lwUtk4dg');
        $swift = Swift_Mailer::newInstance($transport);
        sleep(2);
        $html = "" . $message . "";
        $maildetails = new Swift_Message($subject);
        $maildetails->setFrom($from);
        $maildetails->setBody($html, 'text/html');
        $maildetails->setTo($to);
        $maildetails->addPart($message, 'text/plain');

        if ($recipients = $swift->send($maildetails, $failures)) {
            echo 'Message successfully sent!';
        } else {
            echo "There was an error:n";
            //print_r($failures);
        }
        //mail($my_email,$subject,$message,$headers);
    ?>
    <b>Thank you <?php if(isset($_REQUEST['name'])){print stripslashes($_REQUEST['name']);} ?></b>
    <?php
    }
    else{
        ?>
        <form name = "mail_form" method="post" action ="send_mail.php"enctype="multipart/form-data">
            <div><label for="name"> Full Name: </label> <input name="name" type="text" size="50"  /> </div> 
            <div><label for="address"> Address: </label> <input name="address" type="text" size="50"   /></div>
            <div><label for="email"> Email:  </label><input name="email" type="email" size="50"   /></div>
            <div><label for="contact">Contact:</label>  <input name="contact" type="text"  size="50"  /></div>
            <div><label for="country">Country:</label> <input name="country" type="text"   size="50" /> </div>
            <div><label for="website">Website:</label> <input name="website" type="text"   size="50" /> </div>
            <div><label for="subject">Subject:</label> <input name="subject" type="text"   size="50" /> </div>
            <div><label for="message">Your Message:</label> 
            <textarea name="message" cols="40" rows="8"></textarea>
            </div>
            <div><p><input type="submit" name="btn_submit"  id="submit-go" value="Send Mail"/></p></div>
        </form>
    <?php
    }
    ?>

# i just removed some of the unwanted lines from your code..
You can download swift files from http://ajesh.co.in/downloads/swift.zip

Ajesh VC
  • 635
  • 5
  • 13
  • @Jklyn : visit https://www.mandrill.com/ to learn and download more about mandrill. its also avoid usual spam mails too.. – Ajesh VC Jul 20 '14 at 14:28
  • @Jklyn look here for documentation and downloads :: https://mandrillapp.com/api/docs/index.php.html you need to create an a/c in their web, then only you will get user_name and Mandrill key, that you need to include inside your mail sending code. – Ajesh VC Jul 20 '14 at 14:47
  • had you fixed your issue?? – Ajesh VC Jul 25 '14 at 10:36
  • No not at all. It shows error as: Fatal error: Call to undefined function curl_init() in E:\CMS_Site\wamp\www\sample_site\contents\mandrill-api-php\src\Mandrill.php on line 65 – Jklyn Jul 25 '14 at 18:29
  • Open php.ini(in wamp\apache\bin\) - Remove the semi-colon in front of this line: extension=php_curl.dll - Restart Apache. if it not found or not working just install curl manually. – Ajesh VC Jul 26 '14 at 03:20
  • Removing semi-colon worked but still the contact form isn't working. While sending form, it displays the error as: 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 E:\CMS_Site\wamp\www\sample_site\contents\send_mail.php on line 65 Thank you ABCD – Jklyn Jul 26 '14 at 15:02
  • please update the last modified code with mandrill mail setup. – Ajesh VC Jul 27 '14 at 09:40
  • Did you find any error in the above modified code? @Ajesh VC – Jklyn Jul 31 '14 at 18:44
  • @Jklyn you need to optimise your code further. Any away i have done the solution for you and tested sucessfully .you can view my code in Answer section.You need to download the swift file and include it in your directory where your send_mail.php file exist i too add the download links there. – Ajesh VC Aug 01 '14 at 18:30
  • the above code worked and removed all errors but the mail isn't received. – Jklyn Aug 03 '14 at 09:48
  • 1
    its worked for me.And i think this should not have any problem. You should wait and check the mail in your mail box. did you set To-mail address in line `$to="toemail@mail.com";` in the above code. – Ajesh VC Aug 03 '14 at 12:39
  • I'd set $to="toemail@mail.com"; to $to="kiranpahadi@gmail.com"; I'd waited for a long time but yet I'd not received email. – Jklyn Aug 03 '14 at 16:26
  • Hello @Jklyn i update changes in code with your mail.just copy and paste the whole answer and try. you will get mails in your kiranpahadi@gmail.com mail address.. – Ajesh VC Aug 03 '14 at 16:57
  • It worked... than you so much... only thing to do is I need to place user's mail id instead of frommail@mail.com. I mean the mail id of a person who fill the form. The received mail seems to be like this: T: CONTACT I: 25 Name: Johnny Address: Imadole Email: johnny@gmail.com Contact: 62562562 Subject: test Message: test message... submit: Send Mail -- The Message has been submitted successfully If only
    could be placed at the end, it would look better. Is there any possibilities?
    – Jklyn Aug 03 '14 at 18:26
  • @ Ajesh VC Does this code only sends mail to gmail? Why doesn't it go to info@siteaddress.com? – Jklyn Aug 04 '14 at 10:29
0

WAMP does not have an SMTP server.

Explanation

To be able to send email you need an outgoing email server. In most Linux systems there exists one by default, and PHP will use sendmail, a Linux app for submitting mail to whichever mail transfer agent you have installed.

In Windows, to be able to send mail from PHP you need an outgoing mail server somewhere and you need to tell PHP the address and port of it. This is done in php.ini using the SMTP and smtp_port settings. It will default to 'localhost' on port 25. Unless you have set up a mail server on that machine, that will fail.

If your ISP gives you an outgoing mail server, for example, you could use its address and port number. Or, if you're serious about sending mail, you'd set up your own mail server on the local machine or someone in your local network.

SOURCE Why mail() PHP function does not work with WAMP default installation?

Community
  • 1
  • 1
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37