Scott
Scott

Reputation: 57

PHP Form - Email sent to address from users multiple choice

I have built a PHP form, but want an email to be sent to whatever country the user chooses on a dropdown.

E.g. If they choose UK on dropdown, send an email to our UK account. If they choose US, send to our US account etc...

The entire form is working perfectly at the moment, I just need this little feature to work then it would be perfect. Thank you for looking, its appreciated!

This is my code so far:-

<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');

// configure
// an email address that will be in the From field of the email.
$from = 'A new client has registered their details <[email protected]>';

// an email address that will receive the email with the output of the form
$sendTo = '<[email protected]>';

// subject of the email
$subject = 'New Registered Form:';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = [
    'firstname' => 'First Name', 'lastname' => 'Last Name', 'company' => 'Company', 'email' => 'Email Address', 'jobrole' => 'Job Role',
    'postcode'  => 'Postcode', 'country' => 'Country',
];

// message that will be displayed when everything is OK :)
$okMessage = 'Thank you for registering.';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';

// ReCaptch Secret
$recaptchaSecret = 'AAAA';

// let's do the sending

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);

try
{
    if ( ! empty($_POST))
    {

        // validate the ReCaptcha, if something is wrong, we throw an Exception,
        // i.e. code stops executing and goes to catch() block

        if ( ! isset($_POST['g-recaptcha-response']))
        {
            throw new \Exception('ReCaptcha is not set.');
        }

        // do not forget to enter your secret key from https://www.google.com/recaptcha/admin

        $recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost);

        // we validate the ReCaptcha field together with the user's IP address

        $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);

        if ( ! $response->isSuccess())
        {
            throw new \Exception('ReCaptcha was not validated.');
        }

        // everything went well, we can compose the message, as usually

        $emailText = "This person has registered their details \n=============================\n";

        foreach ($_POST as $key => $value)
        {
            // If the field exists in the $fields array, include it in the email
            if (isset($fields[$key]))
            {
                $emailText .= "$fields[$key]: $value\n";
            }
        }

        // All the neccessary headers for the email.
        $headers = [
            'Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        ];

        // Send email
        mail($sendTo, $subject, $emailText, implode("\n", $headers));

        $responseArray = ['type' => 'success', 'message' => $okMessage];
    }
}
catch (\Exception $e)
{
    $responseArray = ['type' => 'danger', 'message' => $e->getMessage()];
}

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'];
} 
?>

Thank you very much in advance!! Scott Geere

Upvotes: 1

Views: 189

Answers (2)

Ronnie Oosting
Ronnie Oosting

Reputation: 1252

Personally I would do something like this:

switch ($_POST['country']):
case 'UK':
    $sendTo = '<[email protected]>';
    break;
case 'US';
    $sendTo = '<[email protected]>';
    break;
default:
    $sendTo = '<[email protected]>';
endswitch;

Which means you could change:

// an email address that will receive the email with the output of the form
//$sendTo = '<[email protected]>,<[email protected]>';
$sendTo = '<[email protected]>';

To:

// an email address that will receive the email with the output of the form
//$sendTo = '<[email protected]>,<[email protected]>';
switch ($_POST['send_to']):
    case 'UK':
        $sendTo = '<[email protected]>';
        break;
    case 'US';
        $sendTo = '<[email protected]>';
        break;
    default:
        $sendTo = '<[email protected]>';
endswitch;

Please do not forget: never trust the user. So do not just do stuff on $_POST data, make sure you validate the given input before you use it.

Another side note:

Instead of using this raw code in yours, you could make it a function (so you can reuse it somewhere else as well).

For example:

function getSendToEmail($country)
{
    switch ($country):
        case 'UK':
            return '<[email protected]>';
            break;
        case 'US';
            return '<[email protected]>';
            break;
        default:
            return '<[email protected]>';
    endswitch;
}

// an email address that will receive the email with the output of the form
//$sendTo = '<[email protected]>,<[email protected]>';
$sendTo = $this->getSendToEmail($_POST['country']);

Documentation:

Upvotes: 2

Baptiste
Baptiste

Reputation: 1785

if (isset($_POST['country'])) {
    $country = $_POST['country'];
    if ($country === 'France') {
        $sendTo = '[email protected]';
    } elseif ($country === 'England') {
        $sendTo = '[email protected]';
    }
}

You can put it before the mail function.

You can also use an array like that:

$emailList = [
    'France' => '[email protected]',
    'England' => '[email protected]'
];

if (isset($_POST['country'])) {
    // Get email from the key
    $sendTo = $emailList[$_POST['country']];
}

Upvotes: 0

Related Questions