Search code examples
phpemailcontact-formemail-headers

PHP mail header problems


I have two problems currently:

  1. In my gmail, the From: header doesn't respect the 'My contact form' name. It's defaulting to something else.

  2. When I receive the email in gmail, it is of course being sent from [email protected] (to avoid the spam folder), but when I click reply, I want it to use the contact form user's $email, not [email protected]

I'm sure I am missing some details so if I missed something let me know and I will add it.

Here's my code:

if (!isset($_REQUEST['name']) || !isset($_REQUEST['email']) || !isset($_REQUEST['message'])) {
  die();
}

// PHP parameters
$to = "[email protected]";
$name = $_REQUEST['name'] ;
$email = $_REQUEST['email'] ;
$message = $_REQUEST['message'] ;

// Subject
$email_subject = $_POST['name'] . ' ' . 'is contacting you from mywebsite.com' . '!';


// body of email
$body = ""

$body = wordwrap($body, 60, "\n");

// Headers
$headers .= "From: My contact form <[email protected]>" . "\r\n";
$headers .= "Reply-To: $email" . "\r\n";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers .= "Return-Path: [email protected]" . "\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n"; 

// Mail it
mail( $to, $email_subject, $body, $headers, "[email protected]" );

Solution

  • For part 1, the = sets the variable, and then .= adds on to the variable. So, you are overwriting your previously declared variable. It should read:

    $headers = "From: My contact form <[email protected]>" . "\r\n";
    $headers .= "Reply-To: $email" . "\r\n";
    $headers .= "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
    $headers .= "Return-Path: [email protected]" . "\r\n";
    $headers .= "X-Mailer: PHP". phpversion() ."\r\n"; 
    

    For part 2, try this: reply-to address in php contact form

    In other words, change

    $headers .= "Reply-To: $email" . "\r\n";
    

    to

    $headers .= "Reply-To: " . $email . "\r\n";