views:

32

answers:

3

Hi All

I just purchased a website template from DreamTemplate.com, and have tried to send a test e-mail from it online and instead of sending the e-mail it just comes up with red text saying: "ERROR!".

I am not very familiar with PHP, but I can understand the syntax. The code is below:


Contact.html

<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
    $('#contactform').submit(function(){                  
        var action = $(this).attr('action');
        $.post(action, { 
            name: $('#name').val(),
            email: $('#email').val(),
            company: $('#company').val(),
            subject: $('#subject').val(),
            message: $('#message').val()
        },
            function(data){
                $('#contactform #submit').attr('disabled','');
                $('.response').remove();
                $('#contactform').before('<p class="response">'+data+'</p>');
                $('.response').slideDown();
                if(data=='Message sent!') $('#contactform').slideUp();
            }
        ); 
        return false;
    });
});
// ]]>
</script>


Contact.PHP

<?php

if(!$_POST) exit;

$email = $_POST['email'];


//$error[] = preg_match('/\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b/i', $_POST['email']) ? '' : 'INVALID EMAIL ADDRESS';
if(!eregi("^[a-z0-9]+([_\\.-][a-z0-9]+)*" ."@"."([a-z0-9]+([\.-][a-z0-9]+)*)+"."\\.[a-z]{2,}"."$",$email )){
    $error.="You've entered an invalid e-mail address.";
    $errors=1;
}
if($errors==1) echo $error;
else{
    $values = array ('name','email','message');
    $required = array('name','email','message');

    $your_email = "[email protected]";
    $email_subject = "New Message: ".$_POST['subject'];
    $email_content = "new message:\n";

    foreach($values as $key => $value){
      if(in_array($value,$required)){
        if ($key != 'subject' && $key != 'company') {
          if( empty($_POST[$value]) ) { echo 'PLEASE FILL IN REQUIRED FIELDS'; exit; }
        }
        $email_content .= $value.': '.$_POST[$value]."\n";
      }
    }

    if(@mail($your_email,$email_subject,$email_content)) {
        echo 'Message sent!'; 
    } else {
        echo 'ERROR!';
    }
}
?>

Can someone please help? I have no idea why this won't work. Any help at all is much appreciated.

Thank you


Update: As advised, I have removed the @ symbol before 'mail'. It is now displaying useful error messages:

"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:\web\autoopti\contact.php on line 31 ERROR!"

+2  A: 

Your code is failing to send the e-mail message. You need to debug the information that it's getting, so that you have a chance at figuring out what's going on.

First of all, remove the '@' before mail(...). The '@' suppresses (slowly) any errors that the mail() function is spitting out, which means you don't get the information you need to fix it. Ideally, if that function gets properly formed data, you won't have an error. The worst that can happen in that case is the e-mail address provided is malformed.

Then, I'd start debugging the data passed in. Use the echo() function to print out the values of $your_email, $email_subject and $email_content to make sure that they are properly formed. The echo() function is used like:

echo($your_email);
echo($email_subject);
echo($email_content);

You get the idea.

If that doesn't help, or if removing the '@' gives you some funkiness, post back with the error output. That'll help us help you more.

Jason B
+1 for great debugging instructions.
Pekka
+1. Excellent instructions. Thank you heaps. Now I know what's going on! I have updated my question with the new error after removing the @ symbol. Thanks @Jason
lucifer
I'm slightly confused about this email code that was provided. In the error it says that I need to enter smtp stuff etc, but it's no where to be found. I would've thought it would be there since they have put everything else there.
lucifer
@j-t-s: Please see my other answer, it explains SMTP stuff a bit more.
Jason B
@j-t-s: In theory, you shouldn't have to configure anything, if you have a local SMTP/Sendmail server installed. Since you don't, you have two options: install one, or tell PHP to look elsewhere for one.
Jason B
+2  A: 

Posting another answer based on the OP's edit.

Are you running this on your local machine, or on another Windows server? You need to have a SMTP server running on the machine you're trying to execute mail() from. Please see these articles: One Two for basic instructions on setting up an SMTP server, or Google has the answers.

Quick explanation of what an SMTP server is and does: it's the mail relayer. The SMTP server implements the messaging protocols to route e-mails to their appropriate destination(s).

EDIT: If you feel like diving headfirst into PHP, and don't want to bother setting up a local SMTP server, you can use PHPMailer to use your ISP's or another remote SMTP server, where it's already configured for you. There's plenty of sample code out there.

Hope that helps!

Jason B
Thank you very much for the help Jason. I really appreciate it. I'm using the form on my site on the WinHost.com servers (Windows Hosting, but they also support PHP). I am checking out the Worx Int'l site now.
lucifer
@j-t-s: No problem! You may want to see this: https://support.winhost.com/KB/a826/how-to-send-email-from-a-php-application.aspx. Fixing your code to adhere to that would be a very simple change.
Jason B
OOh thank you again :D
lucifer
In the sample code on the winhost support page, it has sample code where i use my password for my account for the smtp stuff. I don't like the idea of my password being publicly available though, is there a way around this?
lucifer
You actually don't have to run a SMTP server on Windows, you can simply edit php.ini and set the value of `SMTP` to your ISP mail server. That will work unless your ISP requires mail authentication - in that case you will have to resort to other solutions (ie. use Zend_Mail, PEAR mail classes, or something similar). BTW Don't forget to restart Apache (or IIS) after this change...
wimvds
@j-t-s: It's not publicly available. The PHP script (if your security is set up right) will not be visible to the outside world, only the HTML it generates, which does not include that password.
Jason B
A: 

Based on the error, it looks like your php.ini configuration for the smtp server is wrong.

You can test it by trying to run a simple PHP script:

<?php
mail("your_email", "Test", "test message")
?>

That removes any doubt about the data that get passed to your mail function.

Now, apart from that, there are a few quirks in your code:

Looking at your jQuery, I can see that you get the message by "val()". That doesn't work on a TextArea, if I remember it right, so it could be a problem if you are using a text area to get the message.

In the PHP code, I suspect this part doesn't work the way you expect it to:

$values = array ('name','email','message');
...
foreach($values as $key => $value){
      if(in_array($value,$required)){
        if ($key != 'subject' && $key != 'company') {
...

Your array specifies no keys, so internally, your array looks like:

[0]=>name;
[1]=>email...

So you end up with if ( 0 != 'subject' && 0 != 'company') {...

However that test is actually useless, because the previous line already makes sure that your value is in the required array, and since "subject" and "company" are not in the required array, that line will never be true.

At the moment, your contact.php does not use the data sent by the jQuery. I assume this is on purpose because you are just testing, right?

Another problem is that you do not validate your data at all. Your form could be used to send spam all over the place using your account. Is that because your function is still at the testing stage?

Sylverdrag
Thank you for your answer. I'm new to sending email in PHP. I only have experience with STMP/POP/IMAP when it comes to C++/C#. So I'm very confused right now. It is still in testing stage. But I didn't actually write this code, it was already there when I bought the website template.
lucifer
@j-t-s: Ah, I understand. PHP is very popular, however one downsides is that there is a lot of the free PHP code/templates of very poor quality.
Sylverdrag