SwiftMailer expects an array of e-mail addresses, possibly including names as values of the array:
$message->setTo([
'[email protected]',
'[email protected]' => 'Person 2 Name',
'[email protected]',
'[email protected]',
'[email protected]' => 'Person 5 Name'
]);
But what I have is a single line of text, forming a standard To
header:
[email protected], 'Person 2 Name' <[email protected]>, [email protected], [email protected], 'Person 5 Name' <[email protected]>
I can probably hack something together to convert the To
header to an array, but this feels like a problem with a standard solution, ideally from someone who has absorbed the RFCs and will accept weird but valid e-mail addresses, including ones that contain commas and semi-colons. Does SwiftMailer itself have a function for this? If so, I can’t find it.
The benefit of using SwiftMailer's typical ->setTo()
API is the validation of the addresses. After validation, SwiftMailer builds the corresponding header and adds it.
/**
* @var $message Swift_Message
*/
$message = $mailer->createMessage();
$message->setTo([
'[email protected]',
'[email protected]' => 'Person 2 Name',
'[email protected]',
'[email protected]',
'[email protected]' => 'Person 5 Name'
]);
// String representation of corresponding To header
print_r((string)$message->getHeaders()->get('To'));
Which yields:
To: [email protected], Person 2 Name <[email protected]>, [email protected], [email protected], Person 5 Name <[email protected]>
It is possible to set headers manually with $message->getHeaders()->addTextHeader()
.
// Set To text-header manually
$message
->getHeaders()
->addTextHeader(
'To',
"[email protected], 'Person 2 Name' <[email protected]>, [email protected], [email protected], 'Person 5 Name' <[email protected]>"
);
// String representation of manually set header
print_r((string)$message->getHeaders()->get('To'));
Which yields the same header. I would personally, however, try to benefit from Swift's validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With