How to add cc and bcc to the following php code

Any PHP experts here ! This code is for website contact form and is working fine at http://www.newsserver.net with the help of html, css, javascript and php, fine but I would like to add blind carbon copy (bcc) and carbon copy (cc) fields to the following php code. Please advice. Best Regards.

<?php

// an email address that will be in the From field of the email.
$from = ‘domain sending mail’;

// an email address that will receive the email with the output of the form
$sendTo = 'recipient email ';

// subject of the email
$subject = ‘WEBSITE CONTACT FORM’;

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array(‘name’ => ‘Name’, ‘surname’ => ‘Surname’, ‘email’ => ‘Email’,‘number’ => ‘Number’, ‘message’ => ‘Message’);

// message that will be displayed when everything is OK :slight_smile:
$okMessage = ‘Contact form successfully submitted !’;

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again ';

// 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(count($_POST) == 0) throw new \Exception('Form is empty');
        
$emailText = "CONTACT FORM \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 = array('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 = array('type' => 'success', 'message' => $okMessage);

}
catch (\Exception $e)
{
$responseArray = array(‘type’ => ‘danger’, ‘message’ => $errorMessage);
}

// if requested by AJAX request return JSON response
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 just display the message echo $responseArray[‘message’];
else {
header(“Location:mywebpage.html”);
}

I personally would use PHPMailer or Swiftmailer as a 3rd Party way of sending email via email as it is easier to understand and to work with. Besides why re-invent the wheel?

This is all I do in my main contact page section:

$submit = filter_input(INPUT_POST, 'submit', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
if (isset($submit) && $submit === 'submit') {
    $token = filter_input(INPUT_POST, 'token', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    if (!empty($token)) {
        if (hash_equals($_SESSION['token'], $token)) {
            /* The Following to get response back from Google recaptcah */
            $url = "https://www.google.com/recaptcha/api/siteverify";

            $remoteServer = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_SANITIZE_URL);
            $response = file_get_contents($url . "?secret=" . PRIVATE_KEY . "&response=" . \htmlspecialchars($_POST['g-recaptcha-response']) . "&remoteip=" . $remoteServer);
            $recaptcha_data = json_decode($response);
            /* The actual check of the recaptcha */
            if (isset($recaptcha_data->success) && $recaptcha_data->success === TRUE) {
                $success = "Mail was sent!";
                $data['name'] = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['email'] = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['phone'] = filter_input(INPUT_POST, 'phone', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['website'] = filter_input(INPUT_POST, 'website', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['reason'] = filter_input(INPUT_POST, 'reason', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
                $data['comments'] = filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

                $send = new Email($data);
            } else {
                $success = "You're not a human!"; // Not of a production server:
            }
        } else {
            // Log this as a warning and keep an eye on these attempts
        }
    }
}

and I set up my class like this:

namespace Library\Email;
/*
 * In order to use swiftmailer the below is needed....
 */
use Swift_SmtpTransport;
use Swift_Message;
use Swift_Mailer;
class Email {

    public $result = \NULL;

    public function __construct(array $data) {
        $this->result = $this->email($data);
    }

    private function email(array $data) {
        /* Setup swiftmailer using your email server information */
        if (filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_URL) == "localhost") {
            $transport = Swift_SmtpTransport::newInstance(EMAIL_HOST, EMAIL_PORT); // 25 for remote server 587 for localhost:
        } else {
            $transport = Swift_SmtpTransport::newInstance(EMAIL_HOST, 25);
        }

        $transport->setUsername(EMAIL_USERNAME);
        $transport->setPassword(EMAIL_PASSWORD);

        /* Setup To, From, Subject and Message */
        $message = Swift_Message::newInstance();

        $name = $data['name'];
        $email_from = $data['email'];
        $subject = $data['reason'] . ' email address ' . $data['email'];
        $comments = $data['phone'] . ' ' . $data['website'] . ' ' . $data['comments'];

        /*
         * Email Address message is going to
         */
        $message->setTo([
           '[email protected]' => 'John Smith'// [email protected] || John Smith
        ]);

        $message->setSubject($subject); // Subject:
        $message->setBody($comments); // Message:
        $message->setFrom($email_from, $name); // From and Name:

        $mailer = Swift_Mailer::newInstance($transport); // Setting up mailer using transport info that was provided:
        $result = $mailer->send($message, $failedRecipients);

        if ($result) {
            return TRUE;
        } else {
            /* Not for production use! */
            echo "<pre>" . print_r($failedRecipients, 1) . "</pre>";
            return FALSE;
        }
    }

}

You can find on how to setup cc and bbc here -> https://swiftmailer.symfony.com/

The javascript/Ajax call I would put in the main php file and NOT the Class file (or procedural code) when a person sends an email.

hello mate! can you guide me to a working example please like to a https://www.pastiebin.com or https://codepen.io/#

just go to the link from @Strider64 head to “documentation” then Creating Messages

I think there is some confusion in understanding my situation, it is so that, the code i have posted is for a website contact form at www.newsserver.net and it is working perfectly fine, all i want to do now is edit it so that i can add a bcc (blind carbon copy field) to the php code, because if i add email ids to the ( $sendTo = ) with a , (comma) separation it shows as two separate addresses in the recipient email address bar … I want to hide bcc in recipient email header… symphony i believe is not a website contact form … kindly correct me if i am wrong … not with javascript validations at least

Sponsor our Newsletter | Privacy Policy | Terms of Service