Mailbox (e-mail address) Headers
Mailbox headers contain one or more email addresses, possibly with personalized names attached to them. The data on which they are modeled is represented by an associative array of email addresses and names.
Mailbox headers are probably the most complex header type to understand in Swift Mailer because they accept their input as an array which can take various forms, as described in Addresses in Swift Mailer.
All of the headers that contain e-mail addresses in a message – with the exception of Return-Path: which has a stricter syntax – use this header type. That is, To:, From: etc.
You add a new mailbox header to a HeaderSet by calling the HeaderSet's addMailboxHeader() method.
<?php
$message = Swift_Message::newInstance();
$headers = $message->getHeaders();
$headers->addMailboxHeader('Your-Header-Name', array(
'person1@example.org' => 'Person Name One',
'person2@example.org',
'person3@example.org',
'person4@example.org' => 'Another named person'
));
Changing the value of an existing mailbox header is done by calling it's setNameAddresses() method.
<?php
$to = $message->getHeaders()->getHeader('To');
$to->setNameAddresses(array(
'joe@example.org' => 'Joe Bloggs',
'john@example.org' => 'John Doe',
'no-name@example.org'
));
If you don't wish to concern yourself with the complicated accepted input formats accepted by setNameAddresses() as described in Addresses in Swift Mailer and you only want to set one or more addresses (not names) then you can just use the setAddresses() method instead.
<?php
$to = $message->getHeaders()->getHeader('To');
$to->setAddresses(array(
'joe@example.org',
'john@example.org',
'no-name@example.org'
));
If all you want to do is set a single address in the header, you can use a string as the input parameter to setAddresses() and/or setNameAddresses().
<?php
$to = $message->getHeaders()->getHeader('To');
$to->setAddresses('joe-bloggs@example.org');
When output via toString(), a mailbox header produces something like the following:
<?php
$to = $message->getHeaders()->getHeader('To');
$to->setNameAddresses(array(
'person1@example.org' => 'Name of Person',
'person2@example.org',
'person3@example.org' => 'Another Person'
));
echo $to->toString();
/*
To: Name of Person <person1@example.org>, person2@example.org, Another Person
<person3@example.org>
*/