简体   繁体   中英

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.

Eg 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 <noreply@emailaddress.com>';

// an email address that will receive the email with the output of the form
$sendTo = '<scott@emailaddress.com>';

// 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

Personally I would do something like this:

switch ($_POST['country']):
case 'UK':
    $sendTo = '<UK@emailaddress.com>';
    break;
case 'US';
    $sendTo = '<US@emailaddress.com>';
    break;
default:
    $sendTo = '<scott@emailaddress.com>';
endswitch;

Which means you could change:

// an email address that will receive the email with the output of the form
//$sendTo = '<helena@dropbox.com>,<l.stone@emeraldcolour.com>';
$sendTo = '<scott@emailaddress.com>';

To:

// an email address that will receive the email with the output of the form
//$sendTo = '<helena@dropbox.com>,<l.stone@emeraldcolour.com>';
switch ($_POST['send_to']):
    case 'UK':
        $sendTo = '<UK@emailaddress.com>';
        break;
    case 'US';
        $sendTo = '<US@emailaddress.com>';
        break;
    default:
        $sendTo = '<scott@emailaddress.com>';
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 '<UK@emailaddress.com>';
            break;
        case 'US';
            return '<US@emailaddress.com>';
            break;
        default:
            return '<scott@emailaddress.com>';
    endswitch;
}

// an email address that will receive the email with the output of the form
//$sendTo = '<helena@dropbox.com>,<l.stone@emeraldcolour.com>';
$sendTo = $this->getSendToEmail($_POST['country']);

Documentation:

if (isset($_POST['country'])) {
    $country = $_POST['country'];
    if ($country === 'France') {
        $sendTo = 'france@emailadress.com';
    } elseif ($country === 'England') {
        $sendTo = 'england@emailadress.com';
    }
}

You can put it before the mail function.

You can also use an array like that:

$emailList = [
    'France' => 'france@emailadress.com',
    'England' => 'england@emailadress.com'
];

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM