8

SwiftMailer expects an array of e-mail addresses, possibly including names as values of the array:

$message->setTo([
  'person1@example.org',
  'person2@example.net' => 'Person 2 Name',
  'person3@example.org',
  'person4@example.org',
  'person5@example.org' => 'Person 5 Name'
]);

But what I have is a single line of text, forming a standard To header:

person1@example.org, 'Person 2 Name' <person2@example.net>, person3@example.org, person4@example.org, 'Person 5 Name' <person5@example.org>

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.

TRiG
  • 10,148
  • 7
  • 57
  • 107
  • Interesting question. I haven't checked Swift Mailer code in a long while but I presume it doesn't compose the actual header until the message is submitted. And creating a custom header yourself will not work because mail server won't search actual recipients there (they must be fed earlier with a special SMTP command). Let's wait and see but I suspect you're out of luck. – Álvaro González Aug 16 '19 at 11:49
  • I've tried to hack something together myself with `imap_rfc822_parse_adrlist()`, but it's pretty tricky. – TRiG Sep 04 '19 at 14:33

1 Answers1

4

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([
    'person1@example.org',
    'person2@example.net' => 'Person 2 Name',
    'person3@example.org',
    'person4@example.org',
    'person5@example.org' => 'Person 5 Name'
]);

// String representation of corresponding To header
print_r((string)$message->getHeaders()->get('To'));

Which yields:

To: person1@example.org, Person 2 Name <person2@example.net>, person3@example.org, person4@example.org, Person 5 Name <person5@example.org>

It is possible to set headers manually with $message->getHeaders()->addTextHeader().

// Set To text-header manually
$message
    ->getHeaders()
    ->addTextHeader(
        'To', 
        "person1@example.org, 'Person 2 Name' <person2@example.net>, person3@example.org, person4@example.org, 'Person 5 Name' <person5@example.org>"
    );

// 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.

Tom
  • 3,281
  • 26
  • 33
  • The input I've got is in this format already, is the thing. I *might* be able to change the way I take input to look more amenable to SwiftMailer, but it'd be tricky to preserve existing values. – TRiG Aug 29 '19 at 09:41