根据下拉选择向收件人发送电子邮件

时间:2015-11-28 19:17:46

标签: php jquery ajax forms contact

尝试根据所选择的状态将此表单发送给某些收件人。此表单将是非盈利的注册表单,并且需要根据注册来自哪个州来某些人。这可能是我与之合作过的最详细的联系表格,后端明智。它使用PHP和ajax。关于什么是有效的任何想法?

 <?php
    // set anti csrf variable
    session_start();
    $_SESSION["token"] = md5(rand(1, 10000).time());
    ?>



    <!-- HTML -->
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="author" content="">
    <title>Job Application Form</title>
    <!-- you can add your own css files here -->
    <link href="../bootstrap-3.2.0/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
    <div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">

            <!-- header -->
            <h1 class="text-center">Job Application Form</h1>

            <!-- Job Application Form -->
            <form action="../api.php" method="post" enctype="multipart/form-data" role="form" id="myForm">

                <!-- result -->
                <div id="note"></div>
                <div class="clearfix"></div>

                <!-- first name -->
                <div class="form-group">
                    <label for="first-name">First Name: </label>
                    <input type="text" name="first-name" id="first-name" class="form-control">
                </div>

                <!-- last name -->
                <div class="form-group">
                    <label for="last-name">Last Name:</label>
                    <input type="text" name="last-name" id="last-name" class="form-control">
                </div>

                <!-- gender -->
                <div class="radio">
                    <label for="male">
                        <input type="radio" name="gender" id="male" value="male">
                        Male
                    </label>
                    <label for="female">
                        <input type="radio" name="gender" id="female" value="female">
                        Female
                    </label>
                </div>

                <!-- telephone -->
                <div class="form-group">
                    <label for="telephone">Telephone: </label>
                    <input type="tel" name="telephone" id="telephone" class="form-control">
                </div>

                <!-- email -->
                <div class="form-group">
                    <label for="email">Email: </label>
                    <input type="email" name="email" id="email" class="form-control">
                </div>
                <!-- address -->
                <div class="form-group">
                    <label for="street-line-1">Street Address</label>
                    <input id="street-line-1" class="form-control" name="street-line-1" type="text">
                </div>
                <div class="form-group">
                    <label for="street-line-2">Street Address Line 2</label>
                    <input id="street-line-3" class="form-control" name="street-line-2" type="text">
                </div>
                <!-- Select Town/City -->
                <div class="form-group">
                    <label for="town-city">Town/City</label>
                    <input id="town-city" class="form-control" name="town-city" type="text">
                </div>
                <!-- Select State -->
                <div class="form-group" name="state">
                    <label for="state">Select State</label>
                    <select id="state" name="state">
                    <option value="AL">Alabama</option>
                    <option value="AK">Alaska</option>
                    <option value="AZ">Arizona</option>
                    <option value="AR">Arkansas</option>
                    <option value="CA">California</option>
                    <option value="CO">Colorado</option>
                    <option value="CT">Connecticut</option>
                    <option value="DE">Delaware</option>
                    <option value="DC">District Of Columbia</option>
                    <option value="FL">Florida</option>
                    <option value="GA">Georgia</option>
                    <option value="HI">Hawaii</option>
                    <option value="ID">Idaho</option>
                    <option value="IL">Illinois</option>
                    <option value="IN">Indiana</option>
                    <option value="IA">Iowa</option>
                    <option value="KS">Kansas</option>
                    <option value="KY">Kentucky</option>
                    <option value="LA">Louisiana</option>
                    <option value="ME">Maine</option>
                    <option value="MD">Maryland</option>
                    <option value="MA">Massachusetts</option>
                    <option value="MI">Michigan</option>
                    <option value="MN">Minnesota</option>
                    <option value="MS">Mississippi</option>
                    <option value="MO">Missouri</option>
                    <option value="MT">Montana</option>
                    <option value="NE">Nebraska</option>
                    <option value="NV">Nevada</option>
                    <option value="NH">New Hampshire</option>
                    <option value="NJ">New Jersey</option>
                    <option value="NM">New Mexico</option>
                    <option value="NY">New York</option>
                    <option value="NC">North Carolina</option>
                    <option value="ND">North Dakota</option>
                    <option value="OH">Ohio</option>
                    <option value="OK">Oklahoma</option>
                    <option value="OR">Oregon</option>
                    <option value="PA">Pennsylvania</option>
                    <option value="RI">Rhode Island</option>
                    <option value="SC">South Carolina</option>
                    <option value="SD">South Dakota</option>
                    <option value="TN">Tennessee</option>
                    <option value="TX">Texas</option>
                    <option value="UT">Utah</option>
                    <option value="VT">Vermont</option>
                    <option value="VA">Virginia</option>
                    <option value="WA">Washington</option>
                    <option value="WV">West Virginia</option>
                    <option value="WI">Wisconsin</option>
                    <option value="WY">Wyoming</option>
                    <option value="other">Other</option>
                    </select> </div>
                <!-- Select Country -->
                <div class="form-group">
                    <label for="country">Select Country</label>
                    <select id="country" name="country">
                    <option selected="" value="">Please Select</option>
                    <option selected="selected" value="United States">United States
                    </option>
                    <option value="other">Other</option>
                    </select> </div>
                <!-- DOB -->
                <div class="form-group">
                    <label for="dob">Date of Birth</label>
                    <input name="dob" id="dob" type="date"> </div>
                <!--Branch of Service-->
                <div class="form-group">
                    <label for="service-branch">Select Branch of Service</label>
                    <select id="service-branch" name="service-branch">
                    <option value="">Please Select</option>
                    <option value="Army Active">Army Active</option>
                    <option value="Army Reserve">Army Reserve</option>
                    <option value="Army Guard">Army Guard</option>
                    <option value="Air Force Active">Air Force Active</option>
                    <option value="Air Force Reserve">Air Force Reserve</option>
                    <option value="Air Guard">Air Guard</option>
                    <option value="Navy Active">Navy Active</option>
                    <option value="Navy Reserve">Navy Reserve</option>
                    <option value="USMC">USMC</option>
                    <option value="USMC Reserve">USMC Reserve</option>
                    <option value="Coast Guard Active">Coast Guard Active
                    </option>
                    <option value="Coast Guard Reserve">Coast Guard Reserve
                    </option>
                    </select> </div>
                <!-- Veteran Status -->
                <div class="form-group">
                    <label for="discharge">Veteran Status</label>
                    <select id="discharge" name="discharge">
                    <option value="">Please Select</option>
                    <option value="Active Duty">Active Duty</option>
                    <option value="Reserve Active Duty">Reserve Active Duty
                    </option>
                    <option value="Reserve/Guard Drill Status">Reserve/Guard Drill 
                    Status</option>
                    <option value="IRR">IRR</option>
                    <option value="Honorable Discharge">Honorable Discharge
                    </option>
                    <option value="Retired-Regular">Retired-Regular</option>
                    <option value="Retired-Medical">Retired-Medical</option>
                    <option value="General-Honorable">General-Honorable</option>
                    <option value="OTH">OTH</option>
                    </select> </div>
                <!-- MOS/Rate -->
                <div class="form-group">
                    <label for="rate-mos">Rate or MOS</label>
                    <input id="rate-mos" class="form-control" name="rate-mos" type="text">
                </div>
                <!-- Years of Service -->
                <div class="form-group">
                    <label for="years-service">Years of Service</label>
                    <input id="years-service" class="form-control" name="years-service" type="text">
                </div>
                <!-- resume -->
                <div class="form-group">
                <p>Please upload a legible copy of your DD-214 or NGB22.  Ensure your Social Security Number is redacted. Discharge type, reason, and re-entry code must be shown.<br>
                Members still serving please upload a redacted copy of your most recent LES statement.</p>
                    <label for="file0">Please upload your DD-214 or NGB-22</label>
                    <input type="file" name="file" id="dd-214_1">
                </div>
                <!--NDA -->
                <div class="form-group">
                NON-DISCLOSURE AGREEMENT
                <textarea name="nda" rows="8" cols="100">
                    This Non-Disclosure Agreement ("Agreement") is made and effective on the day you apply and click "I Agree".  
                    Headings used in this Agreement are provided for convenience only and shall not be used
                    to construe meaning or intent.
                    BY CLICKING "I AGREE" you agree to the terms listed in this Non-Disclosure Agreement 
                    </textarea>
                    <input type="checkbox" name="ndaagreement" value="check" id="ndaagree" /> I have read and agree to the Terms of Warrior Pointe's Non Disclosure Agreement
                    </div>
                    <br><br>
                <!-- Forums -->
                    <h4>Warrior Pointe Forums</h4>
                    <div class="form-group">
                    Forums Terms of Use
                    <textarea name="forumtos" rows="8" cols="100">
                    Please take a moment to review these rules detailed below.  

                    </textarea>
                    </div>
                <!-- Requested forum username -->
                <div class="form-group">
                    <label for="username">Requested Username: </label>
                    <input id="username" class="form-control" name="username" type="username">
                </div>
                <!-- Requested forum password -->
                <div class="form-group">
                    <label for="password">Requested Password: </label>
                    <input id="password" class="form-control" name="password" type="password">
                </div>
                <input type="checkbox" name="forumtos" value="check" id="tosagree" /> I have read and agree to the Forums Terms of Use
                    <br><br>

                <!-- anti csrf tag -->
                <input type="hidden" name="token" id="token" value="<?php echo $_SESSION["token"]; ?>">

                <!-- submit -->
                <button type="submit" class="btn btn-primary" name="submit" id="submit">Submit</button>

            </form>
        </div>
    </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="../jquery-2.1.3.min.js"></script>

    <script src="../form-master/jquery.form.js"></script>

    <!-- Include all compiled plugins (below), or include individual files as needed -->
     <script src="../bootstrap-3.2.0/js/bootstrap.min.js"></script>


     <script type="text/javascript">
    // submit form, the form ID has been used here to access it
    $( "#myForm" ).on('submit', function(e){
        $( "#submit" ).button("loading");
        e.preventDefault();
        $(this).ajaxSubmit({
            target: '#note',
            success:  afterSuccess
        });
    });
    function afterSuccess() {
        $("#submit").button("reset");
        $('html,body').animate({ scrollTop: 0 });
    }

    // anti xss
    $(document).ready(function() {
        if ( top != self )
            top.location.href = self.location.href;
    });
    </script>


    </body>
    </html>` 

这是发件人。

<?php

// When the form is submitted, it should email the inserted contents to some recipients. So set the recipients email addresses here (you can insert multiple emails)
$to = $_POST['state'];

if($state == 'CT') { //if customer was selected
$to = 'hughespj1@gmail.com';
}

else if($state == 'NY') { //if distribution was selected
$to = 'webmaster@warriorpointe.org';
}

else if($department == 'press') { //if press was selected
$to = 'press@email.com';
}

else if($department == 'career') { //if career was selected
$to = 'career@email.com';
}

else if($department == 'other') { //if other was selected
$to = 'other@email.com';
}


// Set email subject here
$subject = "Member Registration Request";



// Set sender's email address
$from = "robot@warriorpointe.org";



// Set default message for beginning of the email
$beginMessage = "";
$beginMessage .= "Hello, <br/>";
$beginMessage .= "The following individual has requested to join Warrior    Pointe.<br/>----------------------"."<br/>";



// Set default message for end of the email
$endMessage = "";
$endMessage .= "----------------------<br/>Best Regards<br/>";
$endMessage .= "Bob The Warrior Pointe Robot";



// Set "true" if you just want to see the required fields in your email, or set "false" if you want to see not required ones too, but their value may be empty if user didn't fill them out
$required = true;



// Set the allowed file extensions for your uploads if you have set an input type "file" in your form. (Please also note that here, you should have as many arrays as you have inputs type "file", for example if you have 2 file upload fields in your form, here just like this sample, you set the allowed file extensions for both of the fields in 2 arrays)
$allowedExts = array(
array("txt", "pdf", "doc"),
array("txt", "pdf", "doc")
);


// Set if the file upload fields in your form are required or not. put "1" if it is required and "0" if it's not required
$requiredUploadFiles = array(
1,
0
);



// Set the maximum file size that is allowed to be uploaded
$maxSize = 2097152;



// Set messages for different circumstances here

// Set failure message in a case that the form has not been sent from a valid resource or due to an error
$error1 = "Could not send email due to an error";

// Set failure message in a case that the email has not been sent
$error2 = "Please insert a valid email address";

// Set failure message in a case that file extension is not allowed
$error3 = "Invalid file type";

// Set failure message in a case that file size is not allowed
$error4 = "File exceeded maximum upload size";

// Set the empty field error
 $error5 = "Please fill out blanks";

// Set success message
$success = "The form has been sent successfully";



// Set your message html tags here (your message will be enclosed between these two tags, and you need to set two kind of tags, one for success and the other for errors)

$errorTag1 = "<div class='alert alert-danger'>";
$errorTag2 = "</div>";

$successTag1 = "<div class='alert alert-success'>";
$successTag2 = "</div>";



 // Here you should set your form required fields. Please be careful about the names that you're going to put inside of this Array, these names must be the same name of the input fields "name" attribute's value
$requiredFields = array(
"email"
);



if ( !isset($_SESSION) ) @session_start();

// for error log
ini_set('error_reporting', E_ALL);
error_reporting(E_ALL);
ini_set('log_errors',TRUE);
ini_set('html_errors',FALSE);
ini_set('error_log','error_log.txt');
ini_set('display_errors',FALSE);

// set variables
$body    = "";
$message = "";
$content = "";
global $check2;
if ( isset($_SESSION["token"]) and isset($_POST["token"]) and       $_SESSION["token"] == $_POST["token"] ) {
// set email
$email = $_POST["email"];
// set form input values
$keys = array();
foreach ( $_POST as $key => $value ) {
    if ( $key != "token" and $key != "submit" and $key != "file" ) {
        if ( $value != "" )
            array_push($keys, $key);
        // create the email body
        if ( is_array($value) ) {
            $countArr = count($value);
            foreach ( $value as $k => $val ) {
                if ( $k == $countArr - 1 )
                    $content .= $val;
                else
                    $content .= $val . ", ";
            }
            $value = ltrim($content, "Array");
        }
        if ( $required == true ) {
            if ( !empty($value) )
                $body .= $key . ": " . trim($value) . "<br/>";
        } else {
            $body .= $key . ": " . trim($value) . "<br/>";
        }
    }
}
// check if the field is required and is not sent
$diff = array_diff($requiredFields, $keys);
foreach ( $diff as $diffObj ) {
    if ( in_array($diffObj, $requiredFields) )
        die($errorTag1.$error5.$errorTag2);
}
// upload file if exists
$upload = false;
$requiredUpload = array();
$arrayCounter = 0;

if ( isset($_FILES["file"]) ) {
    if ( is_array($_FILES["file"]["name"]) ) {
        foreach ( $requiredUploadFiles as $requiredFile ) {
            if ( $requiredFile == 1 )
                $arrayCounter ++;
        }
        // check if the upload is required but no file is sent
        foreach ( $requiredUploadFiles as $uploadKey => $uploadVal ) {
            $check1 = array();
            $check2 = array();
            if ( $uploadVal == 1 )
                array_push($check1, $uploadKey);
            foreach ( $_FILES["file"]["name"] as $k1 => $v1 ) {
                array_push($check2, $k1);
            }
            if ( count(array_diff($check2, $check1)) > 0 ) {
                foreach ( $check1 as $val1 ) {
                    if ( !in_array($val1, $check2))
                        die($errorTag1.$error5.$errorTag2);
                    else {
                        foreach ( $_FILES["file"]["name"] as $keyFile => $name ) {
                            if ( $name != "" ) {
                                array_push($requiredUpload, true);
                            } else
                                array_push($requiredUpload, false);
                        }
                        $upload = in_array(true, $requiredUpload) ? true : false;
                    }
                }
                foreach ( $check2 as $val1 ) {
                    if ( !in_array($val1, $check2))
                        die($errorTag1.$error5.$errorTag2);
                    else {
                        foreach ( $_FILES["file"]["name"] as $keyFile => $name ) {
                            if ( $name != "" ) {
                                array_push($requiredUpload, true);
                            } else
                                array_push($requiredUpload, false);
                        }
                        $upload = in_array(true, $requiredUpload) ? true : false;
                    }
                }
            } else {
                foreach ( $_FILES["file"]["name"] as $keyFile => $name ) {
                    if ( $name != "" ) {
                        array_push($requiredUpload, true);
                    } else
                        array_push($requiredUpload, false);
                }
                $upload = in_array(true, $requiredUpload) ? true : false;
            }
        }
    } else {
        // check if the upload is required but no file is sent
        if ( $requiredUploadFiles[0] == "1" and empty($_FILES["file"]["name"]) )
            die($errorTag1.$error5.$errorTag2);
        else {
            array_push($requiredUpload, true);
            $upload = $_FILES["file"]["name"] != "" ? true : false;
        }
    }
} else {
    foreach ( $requiredUploadFiles as $requiredFile ) {
        if ( $requiredFile == 1 )
            $arrayCounter ++;
    }
    if ( $arrayCounter > 0 )
        die($errorTag1.$error5.$errorTag2);
}
// check file for uploading
if ( $upload ) {
    // set email header and body
    $randomVal = md5(time());
    $mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
    $headers  = "From: ".$from;
    $headers .= "\nMIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/mixed;\n" ;
    $headers .= " boundary=\"{$mimeBoundary}\"";
    $message  = "This is a multi-part message in MIME format.\n\n" .
        "--{$mimeBoundary}\n" .
        "Content-Type: text/html; charset=\"UTF-8\"\n" .
        "Content-Transfer-Encoding: 7bit\n\n".
        $beginMessage . $body . $endMessage . "\n\n"."--{$mimeBoundary}\n";
    //$file_ary = $_FILES['file'];
    // for multiple upload
    if ( is_array($_FILES["file"]["name"]) ) {
        $file_ary = reArrayFiles($_FILES['file'], $check2);
        $count = count($file_ary);
        foreach ( $file_ary as $ex => $file ) {
            if ( $requiredUpload[$ex] == true ) {
                $tmpName = $file['tmp_name'];
                $fileType = $file['type'];
                $fileName = $file['name'];
                $temp = explode(".", $file["name"]);
                $extension = end($temp);
                if ( ($file["size"] < $maxSize ) ) {
                    if ( in_array(strtolower($extension), $allowedExts[$ex]) ) {
                        if ( $file["error"] > 0 ) {
                            // uploading error
                            die($errorTag1.$file["error"].$errorTag2);
                        } else {
                            if ( file($tmpName) ) {
                                $file = fopen($tmpName,'rb');
                                $data = fread($file,filesize($tmpName));
                                fclose($file);
                                $data = chunk_split(base64_encode($data));
                                $message .= "Content-Type: {$fileType};\n" . " name=\"$fileName\"\n" .
                                    "Content-Disposition: attachment;\n" . " filename=\"$fileName\"\n" .
                                    "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                                $message .= $ex == $count - 1 ? "--{$mimeBoundary}--\n" : "--{$mimeBoundary}\n";
                            }
                        }
                    } else {
                        // invalid file type
                        die($errorTag1.$error3.$errorTag2);
                    }
                } else {
                    // reached max-upload-size
                    die($errorTag1.$error4.$errorTag2);
                }
            }
        }
    } else {
        $tmpName = $_FILES['file']['tmp_name'];
        $fileType = $_FILES['file']['type'];
        $fileName = $_FILES['file']['name'];
        $temp = explode(".", $_FILES["file"]["name"]);
        $extension = end($temp);
        if ( ($_FILES["file"]["size"] < $maxSize ) ) {
            if ( in_array(strtolower($extension), $allowedExts[0]) ) {
                if ($_FILES["file"]["error"] > 0) {
                    // uploading error
                    die($errorTag1.$_FILES["file"]["error"].$errorTag2);
                } else {
                    if ( file($tmpName) ) {
                        $file = fopen($tmpName,'rb');
                        $data = fread($file,filesize($tmpName));
                        fclose($file);
                        $data = chunk_split(base64_encode($data));
                        $message .= "Content-Type: {$fileType};\n" . " name=\"$fileName\"\n" .
                            "Content-Disposition: attachment;\n" . " filename=\"$fileName\"\n" .
                            "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
                        $message .= "--{$mimeBoundary}--\n";
                    }
                }
            } else {
                // invalid file type
                die($errorTag1.$error3.$errorTag2);
            }
        } else {
            // reached max-upload-size
            die($errorTag1.$error4.$errorTag2);
        }
    }
} else {
    // set email header and body
    $headers  = "FROM: ".$from."\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
    $message  = $beginMessage . $body . $endMessage;
}
// send email to recipients
//foreach ( $recipients as $recipient ) {
    // recall your function before send emails
    myFunction();
    if ( @mail($to, $subject, $message, $headers) )
        // success in sending email
        $result = $successTag1.$success.$successTag2;
    else
        // error while posting form
        $result = $errorTag1.$error1.$errorTag2;
}
die($result);
} else {
// error while posting form
die($errorTag1.$error1.$errorTag2);
}

// order $_FILES
function reArrayFiles(&$file_post, $indexes)
{
$start = 0;
foreach ( $indexes as $indexKey => $index ) {
    if ( $indexKey == 0 )
        $start = $index;
}
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ( $i = 0; $i < $file_count; $i++ ) {
    foreach ( $file_keys as $key ) {
        $file_ary[$start][$key] = $file_post[$key][$start];
    }
    $start ++;
}
return $file_ary;
}

// here you can write your onw function to be done before sending email
function myFunction() {
// put your codes here
}

0 个答案:

没有答案
相关问题