Search code examples
phpemailphpmailer

PhpMailer, how do I write the variable value correctly for multiple addCC email address?


I have a PhpMailer working code as follow: (short version)
(the variable already defined before hand)

// Sender and recipient settings
$mail->setFrom($pengirim_email, $pengirim_nama);
$mail->addAddress($untuk_email, $untuk_nama);
$mail->addReplyTo($pengirim_email, $pengirim_nama);

Next, I add multiple email address for CC mail:

$mail-->addCC('aaa@gmail.com','Abdul');
$mail-->addCC('bbb@gmail.com','Borat');

It work as expected.

Now since I'm planning that the email address will come from the SQL query, so for the time being I want to know how do I have to fill the SQL 'CarbonCopy' column table with multiple email addresses - by trying to make a "hardcoded" variable value. So I try like this as the replacement for the addCC above:

$tembusan="'aaa@gmail.com','Abdul';'bbb@gmail.com','Borat'"; //not working
$CC = explode(';', $tembusan); //not working
for ($i = 0; $i < count($CC); $i++) {$mail->addCC($CC[$i]);} //not working

But it throw me an error like this :

Error in sending email. Mailer Error: Invalid address: (cc): 'aaa@gmail.com','Abdul'

So I change the $tembusan into like this:

$tembusan="aaa@gmail.com,Abdul;bbb@gmail.com,Borat"; //not working

It gives me almost the same like the error before:

Error in sending email. Mailer Error: Invalid address: (cc): aaa@gmail.com,Abdul

Next, I try also this kind of code :

$tembusan="'aaa@gmail.com','Abdul';'bbb@gmail.com','Borat'"; //not working
$CC = explode(';', $tembusan); //not working
foreach($CC as $CCemail){$mail->AddCC($CCemail;} //not working

And it also throw the same error:

Error in sending email. Mailer Error: Invalid address: (cc): 'aaa@gmail.com','Abdul'

If I echo the last code like this foreach($CC as $CCemail){echo $CCemail. '<br/>';}, it give me a result like this :

'aaa@gmail.com','Abdul'
'bbb@gmail.com','Borat'

In my real code, I have a valid email address. The email address in the code above is just for an example.

Where did I do wrong ?

PS
btw, if I remove the "name" for the email address:

$tembusan="aaa@gmail.com;bbb@gmail.com"; //working
$CC = explode(';', $tembusan); //working
foreach($CC as $CCemail){$mail->AddCC($CCemail;} //working

it runs as expected (but in the gmail, the CC name is aaa and bbb).


Solution

  • Please do a further explode . try

    $tembusan="aaa@gmail.com,Abdul;bbb@gmail.com,Borat"; 
    $CC = explode(';', $tembusan); 
    
    for ($i = 0; $i < count($CC); $i++) {
    $DD = explode(',', $CC[$i]);
    $mail->addCC($DD[0], $DD[1]);
    } 
    

    Please note that I have removed the ' characters . (you may use str_replace of PHP to eliminate these characters)