Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a traditional Email "To" line in SwiftMailer?

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.

like image 333
TRiG Avatar asked Aug 16 '19 09:08

TRiG


1 Answers

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.

like image 199
Tom Avatar answered Nov 20 '22 15:11

Tom