Mario brown Mario brown - 5 months ago 34
PHP Question

Swiftmailer: sending email to multiple recipient

Hello am trying to send email from a contact form through swiftmailer lib. My setup sends mail to single recipient, but when I try sending to more than one email, it throws an error : "


Address in mailbox given [email1@gmail.com,email2@gmail.com] does not
comply with RFC 2822, 3.6.2.


but the two emails are valid according to the specification. Here is the code;

$failed = [];
$sent = 0;
$to = [];

if(isset($_POST['recipients'])){
$recipients = $_POST['recipients'];
}
// Send the message
foreach ((array) $recipients as $to) {

$message ->setTo($to);
$sent += $mailer->send($message, $failed);
}
print_r($recipients);
printf("Sent %d messages\n", $sent);


when I send with one email in the input field print_r($recipients);

gave me an array; "
(Array ( [0] => email1@gmail.com ) Sent 1 messages)
" before but now its not giving array again.
I learnt that foreach expects array, but am not getting array.

at a point I was getting error that 'recipients' is undefined , that is why I added if isset check.

Please How do I send the each email individually ?

Answer Source

It looks like $_POST['recipients'] is a comma separated string. You need to use explode() to split the string on the commas. Casting it as an array won't do that for you:

// We should give $recipients a default value, in case it's empty.
// Otherwise, you would get an error when trying to use it in your foreach-loop
$recipients = [];

if(!empty($_POST['recipients'])){
    // Explode the string
    $recipients =  explode(',', $_POST['recipients']);
}      

// Send the message
foreach ($recipients as $to) {
    // To be safe, we should trim the addresses as well, removing any potential spaces. 
    $message ->setTo(trim($to));
    $sent += $mailer->send($message, $failed);
}