问题
I am trying to send email from a contact form through swiftmailer lib. My setup sends mail to a 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 sent with one email in the input field, print_r($recipients)
gave me this array: (Array ( [0] => email1@gmail.com ) Sent 1 messages)
before but now it's not giving the array.
I learnt that foreach
expects array, but I'm not getting an array.
At one point, I was getting an error that 'recipients' is undefined; that is why I added the if isset()
check.
How do I send the each email individually?
回答1:
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);
}
来源:https://stackoverflow.com/questions/44872196/swiftmailer-sending-email-to-multiple-recipient