Question

I managed to make my contact form work but somehow i cant make it send the message structured how i want...

My code is this:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$messagesubject = $_POST['subject'];
$text = $_POST['text'];

$to = "name@email.com";
$subject = 'Message from a site visitor '.$name;


$content = 'Name: '.$name."\r\n";
$content .= 'E-mail: '.$email."\r\n";
$content .= 'Subject: '.$messagesubject."\r\n";
$content .= 'Message: '.$text."\r\n";


$send_contact=mail($to,$subject,$content);

if($send_contact){
echo "Thank you!";
}
else {
echo "ERROR";
}
?>

I receive a mail but on the senders address (From) is written my e-mail address from the hosting server. If i add $headers ( i created the headers like this: " $headers = 'From: '.$field_email."\r\n"; ") in the mail() than i dont receive any mail...

Please help...

(*i reedited my post)

Was it helpful?

Solution

You have three errors (and one bonus mistake):

  1. You put the body of the message in a variable called $message but use a variable called $text in your mail() function.

  2. You use the wrong variable for your headers. You use $email it should be $headers

  3. Plus it appears you have the variables in your mail() function out of order. Headers go after message body.

  4. You write a variable called $formcontent but never use it. It is redundant with $message anyway.

$send_contact=mail($to,$subject,$message,$headers);

OTHER TIPS

Try This

<?php
    error_reporting(0); 
    if(isset($_POST['submit_button']))
    {     
    $to = 'name@gmail.com';
    $name = $_POST['name'];
    $email = $_POST['email'];
    $msg = $_POST['msg'];
    $subject = $_POST['subject'];

     $message.="Name : $name \n \n";
     $message.="Email : $email \n \n";
     $message.="Message : $msg \n \n";

        $headers = "From: ".$_POST['email']." (My Email Form )";
        if(mail($to, $subject, $message, $headers))
        {
        echo "Thank you!";
        }
        else {
        echo "ERROR";
        }
    }
    ?>
    <form id="contact-form" method="POST">
         <input name="name" type="text" class="form-control" placeholder="Name" required>
         <input name="email" type="email" class="form-control" placeholder="Email" required>
         <input name="subject" type="text" class="form-control" placeholder="Subject" required>
         <textarea name="msg" class="form-control" placeholder="Message" rows="5" cols="30" required></textarea>
        <input type="submit" name="submit_button" value="send"/>
    </form>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top