Horizontt
Horizontt

Reputation: 15

PHP Contact Form - make the Reply-To to have the submitter email

I inspected different topics there, but all of them are not working with my code. I need to get the ability to answer direct to submitter email via my email. Here is my code:

    <?php

// configure
$from = '<[email protected]>';
$sendTo = '<[email protected]>';
$subject = 'New message from PROMO form';
$fields = array('name' => 'Name', 'city' => 'City', 'tel' => 'Tel', 'email' => 'Email', 'message' => 'Message', 'age' => 'Age', 'info' => 'Info', 'checkboxtwo' => 'Checkboxtwo'); // array variable name
$okMessage = 'Спасибо.';
$errorMessage = 'Извините, ошибка.';
$headers = 'From: ' . $fields['email'] . "\r\n" . 'Reply-To: ' . $fields['email'];

try
{
    $emailText = "You have new message from online form form\n=============================\n";

    foreach ($_POST as $key => $value) {

        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    mail($sendTo, $subject, $emailText, $headers);

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
else {
    echo $responseArray['message'];
}

I will highly appreciate any help. Thank you.

Upvotes: 1

Views: 134

Answers (1)

Vincius Oliveira
Vincius Oliveira

Reputation: 59

THE ANSWER

Re-write your foreach like this:

foreach ($_POST as $key => $value) {
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
            $fields[$key] = $value; //It set the values on the array
        }
}

Then add the headers:

$headers = 'From: ' . $fields['email'] . "\r\n" . 'Reply-To: ' . $fields['email'];

So just send the mail.

mail($sendTo, $subject, $emailText, $headers);

Other answers (ignore them)

Just set the headers with the "Reply-To".

$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from;

mail($sendTo, $subject, $emailText, $headers);

You will get any replies to the email that you used to submit the message.

EDIT

Get the desired email by using this:

$sendTo = $fields['email'];

Then you will be able to send the email using this var.

Upvotes: 1

Related Questions