1

I'm pretty new to PHP and getting to grips with a (very simple) contact form. When I uploaded this to my hosting company, the PHP script does run as when I fill out and submit the form it brings back my confirmation but the email does not send. My hosting company is 123-reg. Do I have to do anything with them to allow the email to be sent?

My code is as follows:

Form Code:

    <form action="action_handler.php" method="POST">
    <dl>
    <dt> Name:
    <dd><input type="text" name="name">
    <dt> Email Address:
    <dd><input type="text" name="mail">
    <dt> Comments:
    <dd><textarea rows="5" cols "20" name="comment">
    </textarea>
    </dl>
    <p><input type="submit"></p>
    </form> 

PHP Code:

    <?php
    $name = $_POST['name'];
    $mail = $_POST['mail'];
    $comment = $_POST['comment'];

    $to = "someone@hotmail.co.uk";
    $subject = "Contact Form Request";
    $body = "You have a new message from: /n Name: $name /n Email: $mail /n/nThe request is as follows: /n/n $comment";

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

    echo"<p>Thanks for your comment $name ...</p>";
    echo"<p><i>$comment</i></p>";
    echo"<p>We will reply to $mail</p>";
    ?>

Any help is much appreciated.

jww
  • 97,681
  • 90
  • 411
  • 885
Chris
  • 25
  • 4

1 Answers1

1

There are a few things wrong with your present code.

Firstly, /n which should read as \n very important. It's a syntax error.

Then, there's the missing From: which not having that in mail headers, will most likely be rejected or sent to spam.

The "from" in mail will end up being an email address from "@yourserver.xxx"

To include a From: use the following:

$header = "From: ". $name . " <" . $mail . ">\r\n";

which will show up as the person's name in the "from", yet identified as a proper email address.

More often than none, mail is sent to spam whenever From: is omitted from headers.

Therefore

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

should be modified to

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

including the line above, to be inserted underneath the $body variable.

For more information on mail/headers, visit:

Add error reporting to the top of your file(s) which will help find errors.

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.


You can also use a conditional statement to check if mail was indeed sent:

if(mail ($to,$subject,$body,$header)) { 
    echo "Sent."; 
    } else{ 
    echo "Sorry, check your mail logs."; 
}

Once mail goes out, it's out of your server's hands and into the receiver's end. There's nothing you can do "after the fact."

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141