Send emails to multiple recipients

Hello there,

I need to send my forms to multiple recipients, but I can’t figure it out which line I need to edit. Please see below. I appreciate your help.

<?php
// Configure your Subject Prefix and Recipient here


$errors = array(); // array to hold validation errors
$data   = array(); // array to pass back data

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subjectPrefix = $_POST['subject'];
    $privacyPolicy = $_POST['privacy-policy'];
    $emailTo = stripslashes(trim($_POST['email-to']));
    $name    = stripslashes(trim($_POST['name']));
    $email   = stripslashes(trim($_POST['email']));
	$phone   = stripslashes(trim($_POST['phone']));
    $message = stripslashes(trim($_POST['message']));
    $spam    = $_POST['textfield'];
    $confirmMsg = $_POST['confirm'];
    $captcha = $_POST['captcha'];

    if (empty($name)) {
        $errors['name'] = 'Please fill in all required fields.';
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors['email'] = 'Please fill in all required fields.';
    }

    if (empty($message)) {
        $errors['message'] = 'Please fill in all required fields.';
    }
    
    if (empty($captcha)) {
        $errors['captcha'] = 'TEST CAPTCHA';
    }

    if (empty($privacyPolicy)) {
        $errors['privacy_policy'] = 'Please fill in all required fields.';
    }

    // if there are any errors in our errors array, return a success boolean or false
    if (!empty($errors)) {
        $data['success'] = false;
        $data['errors']  = $errors;
    } else {
        $subject = "Message from $subjectPrefix";
        $body    = '
            <strong>Name: </strong>'.$name.'<br />
            <strong>Email: </strong>'.$email.'<br />
			<strong>Phone: </strong>'.$phone.'<br />
            <strong>Message: </strong>'.nl2br($message).'<br />
        ';

        $headers  = "MIME-Version: 1.1" . PHP_EOL;
        $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
        $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
        $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
        $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
        $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
        $headers .= "Return-Path: $emailTo" . PHP_EOL;
        $headers .= "Reply-To: $email" . PHP_EOL;
        $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
        $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;


        if (empty($spam)) {
          mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
        }

        $data['success'] = true;
        $data['confirmation'] = $confirmMsg;
    }

    // return all our data to an AJAX call
    echo json_encode($data);
}

Well, it’s the $emailTo variable that holds the email address you’re sending to, so that’s what you need to change. You don’t show your form, but that is probably going to need some amendment to allow the entry of more than one email address.

How many recipients to intend to have?

Thanks. I wan to include up to 3 emails. I tried editing this line $emailTo = "test@test.com,test2@test.com";, but it didn’t work. I don’t get the emails.

here’s my form.

<?php

$kou_contact_validation = get_field( 'kou_contact_validation', 'option' );
$kou_contact_settings = get_field( 'kou_sidebar_contact-form', 'option' );

$kou_email_to = esc_html( $kou_contact_settings['email'] );
$kou_subject = esc_html( $kou_contact_settings['subject'] );
$kou_confirm = $kou_contact_validation['confirm'] ? esc_html( $kou_contact_validation['confirm'] ) : 'We have sent you a confirmation email';

$kou_is_captcha = get_field( 'kou_captcha_contact_enabled', 'option' );
$kou_is_privacy_policy = get_field( 'kou_gdpr_status', 'option' );

?>

<script type="text/javascript">

/* _____________________________________

    Contact Form
_____________________________________ */

(function ($, window, document, undefined) {
  'use strict';

  var form = $('#contact-form'),
    messageContainer = $('#message-contact'),
    messageText = $('#message-contact .message-text');

  form.on('submit', function (e) {

    // remove the error class
    form.find('.form-group').removeClass('error');
    form.find('#contact-captcha').removeClass('error');
    form.find('.form__policy').removeClass('error');
    messageContainer.removeClass('error');

    var errorAll = '';

    // get the form data
    var formData = {
      'name': $('input[name="form-name"]').val(),
      'email': $('input[name="form-email"]').val(),
	  'phone': $('input[name="form-phone"]').val(),
      'message': $('textarea[name="form-message"]').val(),
      'textfield': $('input[name="text-field"]').val(),
      'subject': '<?php echo $kou_subject; ?>',
      'email-to': '<?php echo sanitize_email( $kou_email_to ); ?>',
      'confirm': '<?php echo esc_html( $kou_confirm ); ?>',
    };

    if('<?php echo $kou_is_captcha; ?>' == 'captcha') {
      formData['captcha'] = $('input[name="contact-captcha"]').val();
    } else {
      formData['captcha'] = 'NO CAPTCHA';
    }
    if('<?php echo $kou_is_privacy_policy; ?>' == 'enable') {
      formData['privacy-policy'] = $('input[name="privacy-policy"]').serialize();
    } else {
      formData['privacy-policy'] = 'privacy-policy:off'
    }

    // process the form
    $.ajax({
      type: 'POST',
      url: 'wp-content/plugins/kounter/includes/functions/contact-process.php',
      data: formData,
      dataType: 'json',
      encode: true
    }).done(function (data) {
      // handle errors
      if (!data.success) {
        if (data.errors.name) {
          $('#name-field').addClass('error');
          errorAll = data.errors.name;
        }
        if (data.errors.email) {
          $('#email-field').addClass('error');
          errorAll = data.errors.email;
        }
		if (data.errors.phone) {
          $('#phone-field').addClass('error');
          errorAll = data.errors.phone;
        }
        if (data.errors.message) {
          $('#message-field').addClass('error');
          errorAll = data.errors.message;
        }
        if (data.errors.captcha) {
          form.find('#newsletter-captcha').addClass('error');
          errorAll = data.errors.captcha;
        }
        if (data.errors.privacy_policy) {
          form.find('.form__policy').addClass('error');
          errorAll = data.errors.privacy_policy;
        }
        messageContainer.addClass('error');
        messageText.html(errorAll);
      } else {
        // display success message
        messageText.html(data.confirmation);

        $('#contact-form .form-control').each(function () {
          $(this).fadeIn().val($(this).attr('placeholder'));
        });
      }
      messageContainer.slideDown('slow', 'swing');
      setTimeout(function () {
        messageContainer.slideUp('slow', 'swing');
      }, 3000);
    }).fail(function (data) {
      // for debug
      console.log(data)
    });

    e.preventDefault();
  });
}(jQuery, window, document));

</script>

Well, $emailTo = "test@test.com,test2@test.com"; is the correct format. I don’t know why that should not work. TBH PHP’s mail() function can be fraught with difficulties and it might be better to use something like PHPMailer. It requires more code, but it is easier to add multiple recipients.

Aside:
To format your code, the <code> tag does not work properly. You need to either use three backticks ``` before and after your code, or highlight the code and click the </> link.

I agreed. I ended up editing my ajax form and edited this line

‘email-to’: ‘email1@domain.com,email2@domain2.com’,

The only issue I have now, i can’t enter anything on the message textarea field unless i TAB on my keyboard, if i cuse my mouse doesn;t work. here’s an example. https://prnt.sc/11auk3m

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.