When trying to send a message with Zend\Mail
to multiple BCC
or CC
recipients, only the first recipient in the list will receive the email. Multiple normal recipients aren't a problem.
$mail = new Mail\Message();
$mail->setBcc([
'bcc_recipient_one@example.com',
'bcc_recipient_two@example.com',
'bcc_recipient_three@example.com',
]);
It doesn't make a difference to use setBcc
or addBcc
of the Message
object.
The Issue
The problem belongs to a wrong format of the Zend\Mail
header generation. It uses line-breaks
between all CC
or BCC
recipients. As fully described in this post, the workaround is to fix the folding.
For example, this snippet:
$mail = new Mail\Message();
$mail->setFrom('test@stackoverflow.com', 'Stackoverflow Tester');
$mail->addTo('email@stackoverflow.com', 'Stackoverflow Recipient');
$mail->setSubject('Stackoverflow Test');
$mail->setBcc(['bcc_one@so.com', 'bcc_two@so.com', 'bcc_three@so.com']);
Will create such header:
Date: Wed, 18 Jan 2018 19:11:36 +0100
From: Stackoverflow Tester <test@stackoverflow.com>
To: email@stackoverflow.com
Subject: Stackoverflow Test
Bcc: bcc_one@so.com,
bcc_two@so.com,
bcc_three@so.com
The problem, for at least some servers (like Micrsoft Exchange), is the line-breaks after the recipients. To fix this issue, the best way IMO would be an own Header class, because the line-breaks are hard-coded in Zend\Mail.
The Solution
Just copy \Zend\Mail\Header\Bcc
class to your module and overwrite the getFieldValue
function in there. With this approach you will be stay compatible on updates in the future.
public function getFieldValue($format = HeaderInterface::FORMAT_RAW)
{
$value = parent::getFieldValue($format);
return str_replace(Headers::FOLDING, ' ', $value);
}
The recipients will now be passed by the new header class to the Message
object.
$bcc = new \MyModule\Header\Bcc();
$bcc->getAddressList()->addMany(['bcc_one@so.com', 'bcc_two@so.com', 'bcc_three@so.com']);
$mail->getHeaders()->addHeader($bcc);
That's it, the new header will be generated correctly:
Date: Wed, 18 Jan 2018 19:11:36 +0100
From: Stackoverflow Tester <test@stackoverflow.com>
To: email@stackoverflow.com
Subject: Stackoverflow Test
Bcc: bcc_one@so.com, bcc_two@so.com, bcc_three@so.com
For more details about the issue and the solution, take a look to the original post.