首页 > 解决方案 > PHP 表单 - 发送到用户多选地址的电子邮件

问题描述

我已经构建了一个 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'];
} 
?>

非常感谢您提前!!斯科特·吉尔

标签: phphtmlformsdropdown

解决方案


我个人会做这样的事情:

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

文档:


推荐阅读