Skip to content
Advertisement

Sending emails to multiple addresses using config PHP file and PHP Mailer

I setup a config.php file to make it easy for my clients to add emails, subject and other sending information for an online form on their website. It looks like this:

<?php
$config = [
    "host" => "xxx",
    "username" => "xxx",
    "password" => "xxx",
    "secure" => "ssl", // ssl or tls
    "port" => 465,
    "sendTo" => "abc@email.com",
    "sendToBCC" => "xyz@email.com",
    "from" => "no-reply@email.com",
    "fromName" => "Contact Form"
];

The challenge I am having now is sending to multiple emails. I tried "sendTo" => "abc@email.com, efg@email.com, hik@email.com", but it throws up invalid email error.

In the sending file, we have the code below:

//Recipients
$mail->setFrom($config['from'], $config['fromName']);
$mail->addAddress($config['sendTo']);
$mail->addCC($config['sendToCC']);          
$mail->addBCC($config['sendToBCC']);
$mail->addAddress($_POST['email']);

So I am guessing the line $mail->addAddress($config['sendTo']); is having trouble picking multiple emails. How do we edit this code to allow for multiple recipients? Will very much like to ensure that our clients can easily add emails in the config.php file instead of the sending file.

Advertisement

Answer

Based on the examples from PHPMailer courtesy of the link shared by @Chris Haas. I made these changes:

<?php
$config = [
    "host" => "xxx",
    "username" => "xxx",
    "password" => "xxx",
    "secure" => "ssl", // ssl or tls
    "port" => 465,
    "sendTo" => "abc@email.com",
    "sendTo2" => "efg@email.com",
    "sendTo3" => "hik@email.com",
    "sendToBCC" => "xyz@email.com",
    "from" => "no-reply@email.com",
    "fromName" => "Contact Form"
];

And in the sending file I did this:

//Recipients
$mail->setFrom($config['from'], $config['fromName']);
$mail->addAddress($config['sendTo']);
$mail->addAddress($config['sendTo2']);
$mail->addAddress($config['sendTo3']);
$mail->addCC($config['sendToCC']);          
$mail->addBCC($config['sendToBCC']);
$mail->addAddress($_POST['email']);

That resolved the issue.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement