PHP Send-Mail form to multiple email addresses

前端 未结 3 1042
醉话见心
醉话见心 2021-01-14 09:38

I\'m very new to PHP and am using a basic template \'send-mail\' form on a contact page. It\'s been requested that I send the email out to multiple email addresses when the

3条回答
  •  爱一瞬间的悲伤
    2021-01-14 10:08

    Here is a simple example:

    
    if (isset($_POST['formSubmit'])) {
        // Set some variables
        $required_fields = array('name', 'email');
        $errors = array();
    
        $success_message = "Congrats! Your message has been sent successfully!";
        $sendmail_error_message = "Oops! Something has gone wrong, please try later.";
    
        // Cool the form has been submitted! Let's loop through the required fields and check
        // if they meet our condition(s)
        foreach ($required_fields as $fieldName) {
            // If the current field in the loop is NOT part of the form submission -OR-
            // if the current field in the loop is empty, then...
            if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
    
                // add a reference to the errors array, indicating that these conditions have failed
                $errors[$fieldName] = "The {$fieldName} is required!";
            }
        }
    
        // Proceed if there aren't any errors
        if (empty($errors)) {
            $name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
            $email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
    
            // Email Sender Settings
            $to_emails = "anonymous1@example.com, anonymous2@example.com";
    
            $subject = 'Web Prayer Request from ' . $name;
            $message = "From: {$name}";
            $message .= "Email: {$email}";
    
            $headers = "From: {$name}\r\n";
            $headers .= "Reply-To: {$email}\r\n";
            $headers .= 'X-Mailer: PHP/' . phpversion();
    
            if (mail($to_emails, $subject, $message, $headers)) {
                echo $success_message;
            } else {
                echo $sendmail_error_message;
            }
        } else {
    
            foreach($errors as $invalid_field_msg) {
                echo "

    {$invalid_field_msg}

    "; } } }

提交回复
热议问题