如何根据选择使用联系表单将电子邮件发送到不同的地址

时间:2017-04-26 17:54:41

标签: javascript php twitter-bootstrap email

我正在开发一个bootstrap网页。我需要能够将联系表单消息发送到电子邮件地址,具体取决于下拉列表中的选择。例如,如果他们选择联系Church,那么电子邮件需要发送到church@emailaddress.com,如果他们选择了School,那么它会转到school@emailaddress.com,如果他们选择了Preschool,那么它会转到学前班@emailaddress .COM。我没有使用PHP和很少JS的经验。

以下是我的代码......

HTML:

<div class="row">
        <div class="col-md-12">
            <form name="sentMessage" id="contactForm" novalidate>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Name</label>
                        <input type="text" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
                        <p class="help-block text-danger"></p>
                    </div>
                 </div>
                 <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Email Address</label>
                        <input type="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Phone Number</label>
                        <input type="tel" class="form-control" placeholder="Phone Number" id="phone" required data-validation-required-message="Please enter your phone number.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Who do you wish to contact?</label>
                        <select class="form-control empty" id="selectDept" name="deptid">
                            <option>SELECT...</option>
                            <option>Faith Lutheran Church</option>
                            <option>K-5 School</option>
                            <option>Touching Hearts Preschool</option>
                        </select>
                    </div>
                </div>
                <div class="row control-group">
                    <div class="form-group col-xs-12 floating-label-form-group controls">
                        <label>Message</label>
                        <textarea rows="5" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <br> 

                <img id="captcha" src="/securimage/securimage_show.php" alt="CAPTCHA Image" />
                <input type="text" name="captcha_code" size="10" id="captcha_code" maxlength="6" />
                <a href="#" onclick="document.getElementById('captcha').src = '/securimage/securimage_show.php?' + Math.random(); return false"><span class="captchaImage"><i class="fa fa-refresh"></i></span></a>

                <br>
                <br>
                <div id="success"></div>
                   <div class="row">
                        <div class="form-group col-xs-12">
                            <button type="submit" class="btn btn-success btn-lg">Send</button>
                        </div>
                    </div>
            </form>
        </div>
    </div>

PHP:

<?php
session_start();
$response = array('error' => true, 'message' => 'OK');

// Check for empty fields
if(empty($_POST['name'])        ||
empty($_POST['email'])      ||
empty($_POST['phone'])      ||
empty($_POST['message'])    ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
    $response['message'] = "No arguments Provided!";
    die(json_encode($response));
}

include_once $_SERVER['DOCUMENT_ROOT'] . '/securimage/securimage.php';
$securimage = new Securimage();

if ($securimage->check($_POST['captcha_code']) == false) {
  // the code was incorrect
    $response['message'] = "The security code entered was incorrect.";
    die(json_encode($response));
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];

// Create the email and send the message
$to = 'church@emailaddress.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Question from Website:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";
$headers = "From: noreply@emailaddress.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address"; 
mail($to,$email_subject,$email_body,$headers);

$response['error'] = false;

die(json_encode($response));

?>

JS:

$(function() {

    $("input,textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            // Prevent spam click and default submit behaviour
            $("#btnSubmit").attr("disabled", true);
            event.preventDefault();

            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var captcha_code = $("input#captcha_code").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                dataType: 'json',
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    captcha_code: captcha_code,
                    message: message
                },
                cache: false,
                success: function(response) {
                    if (response.error) {

                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>The security code enstered was incorrect.");
                    $('#success > .alert-danger').append('</div>');
                    } else {
                    // Enable button & show success message
                    $("#btnSubmit").attr("disabled", false);
                    $('#success').html("<div class='alert alert-success'>");
                    $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-success')
                        .append("<strong>Your message has been sent. </strong>");
                    $('#success > .alert-success')
                        .append('</div>');

                    //clear all fields
                    $('#contactForm').trigger("reset");
                        }
                },
                error: function() {
                    // Fail message
                    $('#success').html("<div class='alert alert-danger'>");
                    $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                        .append("</button>");
                    $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
                    $('#success > .alert-danger').append('</div>');
                    //clear all fields
                    $('#contactForm').trigger("reset");
                },
            })
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});

// When clicking on Full hide fail/success boxes
$('#name').focus(function() {
    $('#success').html('');
});

1 个答案:

答案 0 :(得分:0)

您可以在选项标记中将该电子邮件添加为值:

<option value="email address here">Church</option>

然后在JS中你可以通过以下方式获得值:

var emailAdd = $('#selectDept').val();

并将其传递给您,就像您通过其他属性一样联系php。