PHP Form - электронная почта отправляется на адрес от пользователей с множественным выбором - PullRequest
0 голосов
/ 30 августа 2018

Я создал форму PHP, но хочу, чтобы электронное письмо отправлялось в любую страну, которую пользователь выбрал в раскрывающемся списке.

например. Если они выберут Великобританию в выпадающем списке, отправьте электронное письмо на наш счет в Великобритании. Если они выбирают США, отправьте их на наш счет в США и т. Д. *

В настоящее время вся форма работает отлично, мне просто нужна эта небольшая функция, чтобы она была идеальной. Спасибо за внимание, это ценится!

Это мой код: -

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

Большое спасибо заранее !! Скотт Гир

Ответы [ 2 ]

0 голосов
/ 30 августа 2018

Лично я бы сделал что-то вроде этого:

switch ($_POST['country']):
case 'UK':
    $sendTo = '<UK@emailaddress.com>';
    break;
case 'US';
    $sendTo = '<US@emailaddress.com>';
    break;
default:
    $sendTo = '<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 = '<scott@emailaddress.com>';

Кому:

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

Пожалуйста, не забывайте: никогда не доверяйте пользователю. Так что не просто делайте что-то с данными $_POST, убедитесь, что вы проверяете данные, прежде чем использовать их.

Другая примечание:

Вместо того, чтобы использовать этот необработанный код в вашем, вы можете сделать его функцией (чтобы вы могли использовать его и в другом месте).

Например:

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']);

Документация:

0 голосов
/ 30 августа 2018
if (isset($_POST['country'])) {
    $country = $_POST['country'];
    if ($country === 'France') {
        $sendTo = 'france@emailadress.com';
    } elseif ($country === 'England') {
        $sendTo = 'england@emailadress.com';
    }
}

Вы можете поставить его перед функцией mail.

Вы также можете использовать такой массив:

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

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