headers.rst 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. Message Headers
  2. ===============
  3. Sometimes you'll want to add your own headers to a message or modify/remove
  4. headers that are already present. You work with the message's HeaderSet to do
  5. this.
  6. Header Basics
  7. -------------
  8. All MIME entities in Swift Mailer -- including the message itself --
  9. store their headers in a single object called a HeaderSet. This HeaderSet is
  10. retrieved with the ``getHeaders()`` method.
  11. As mentioned in the previous chapter, everything that forms a part of a message
  12. in Swift Mailer is a MIME entity that is represented by an instance of
  13. ``Swift_Mime_MimeEntity``. This includes -- most notably -- the message object
  14. itself, attachments, MIME parts and embedded images. Each of these MIME entities
  15. consists of a body and a set of headers that describe the body.
  16. For all of the "standard" headers in these MIME entities, such as the
  17. ``Content-Type``, there are named methods for working with them, such as
  18. ``setContentType()`` and ``getContentType()``. This is because headers are a
  19. moderately complex area of the library. Each header has a slightly different
  20. required structure that it must meet in order to comply with the standards that
  21. govern email (and that are checked by spam blockers etc).
  22. You fetch the HeaderSet from a MIME entity like so:
  23. .. code-block:: php
  24. $message = Swift_Message::newInstance();
  25. // Fetch the HeaderSet from a Message object
  26. $headers = $message->getHeaders();
  27. $attachment = Swift_Attachment::fromPath('document.pdf');
  28. // Fetch the HeaderSet from an attachment object
  29. $headers = $attachment->getHeaders();
  30. The job of the HeaderSet is to contain and manage instances of Header objects.
  31. Depending upon the MIME entity the HeaderSet came from, the contents of the
  32. HeaderSet will be different, since an attachment for example has a different
  33. set of headers to those in a message.
  34. You can find out what the HeaderSet contains with a quick loop, dumping out
  35. the names of the headers:
  36. .. code-block:: php
  37. foreach ($headers->getAll() as $header) {
  38. printf("%s<br />\n", $header->getFieldName());
  39. }
  40. /*
  41. Content-Transfer-Encoding
  42. Content-Type
  43. MIME-Version
  44. Date
  45. Message-ID
  46. From
  47. Subject
  48. To
  49. */
  50. You can also dump out the rendered HeaderSet by calling its ``toString()``
  51. method:
  52. .. code-block:: php
  53. echo $headers->toString();
  54. /*
  55. Message-ID: <1234869991.499a9ee7f1d5e@swift.generated>
  56. Date: Tue, 17 Feb 2009 22:26:31 +1100
  57. Subject: Awesome subject!
  58. From: sender@example.org
  59. To: recipient@example.org
  60. MIME-Version: 1.0
  61. Content-Type: text/plain; charset=utf-8
  62. Content-Transfer-Encoding: quoted-printable
  63. */
  64. Where the complexity comes in is when you want to modify an existing header.
  65. This complexity comes from the fact that each header can be of a slightly
  66. different type (such as a Date header, or a header that contains email
  67. addresses, or a header that has key-value parameters on it!). Each header in the
  68. HeaderSet is an instance of ``Swift_Mime_Header``. They all have common
  69. functionality, but knowing exactly what type of header you're working with will
  70. allow you a little more control.
  71. You can determine the type of header by comparing the return value of its
  72. ``getFieldType()`` method with the constants ``TYPE_TEXT``,
  73. ``TYPE_PARAMETERIZED``, ``TYPE_DATE``, ``TYPE_MAILBOX``, ``TYPE_ID`` and
  74. ``TYPE_PATH`` which are defined in ``Swift_Mime_Header``.
  75. .. code-block:: php
  76. foreach ($headers->getAll() as $header) {
  77. switch ($header->getFieldType()) {
  78. case Swift_Mime_Header::TYPE_TEXT: $type = 'text';
  79. break;
  80. case Swift_Mime_Header::TYPE_PARAMETERIZED: $type = 'parameterized';
  81. break;
  82. case Swift_Mime_Header::TYPE_MAILBOX: $type = 'mailbox';
  83. break;
  84. case Swift_Mime_Header::TYPE_DATE: $type = 'date';
  85. break;
  86. case Swift_Mime_Header::TYPE_ID: $type = 'ID';
  87. break;
  88. case Swift_Mime_Header::TYPE_PATH: $type = 'path';
  89. break;
  90. }
  91. printf("%s: is a %s header<br />\n", $header->getFieldName(), $type);
  92. }
  93. /*
  94. Content-Transfer-Encoding: is a text header
  95. Content-Type: is a parameterized header
  96. MIME-Version: is a text header
  97. Date: is a date header
  98. Message-ID: is a ID header
  99. From: is a mailbox header
  100. Subject: is a text header
  101. To: is a mailbox header
  102. */
  103. Headers can be removed from the set, modified within the set, or added to the
  104. set.
  105. The following sections show you how to work with the HeaderSet and explain the
  106. details of each implementation of ``Swift_Mime_Header`` that may
  107. exist within the HeaderSet.
  108. Header Types
  109. ------------
  110. Because all headers are modeled on different data (dates, addresses, text!)
  111. there are different types of Header in Swift Mailer. Swift Mailer attempts to
  112. categorize all possible MIME headers into more general groups, defined by a
  113. small number of classes.
  114. Text Headers
  115. ~~~~~~~~~~~~
  116. Text headers are the simplest type of Header. They contain textual information
  117. with no special information included within it -- for example the Subject
  118. header in a message.
  119. There's nothing particularly interesting about a text header, though it is
  120. probably the one you'd opt to use if you need to add a custom header to a
  121. message. It represents text just like you'd think it does. If the text
  122. contains characters that are not permitted in a message header (such as new
  123. lines, or non-ascii characters) then the header takes care of encoding the
  124. text so that it can be used.
  125. No header -- including text headers -- in Swift Mailer is vulnerable to
  126. header-injection attacks. Swift Mailer breaks any attempt at header injection by
  127. encoding the dangerous data into a non-dangerous form.
  128. It's easy to add a new text header to a HeaderSet. You do this by calling the
  129. HeaderSet's ``addTextHeader()`` method.
  130. .. code-block:: php
  131. $message = Swift_Message::newInstance();
  132. $headers = $message->getHeaders();
  133. $headers->addTextHeader('Your-Header-Name', 'the header value');
  134. Changing the value of an existing text header is done by calling it's
  135. ``setValue()`` method.
  136. .. code-block:: php
  137. $subject = $message->getHeaders()->get('Subject');
  138. $subject->setValue('new subject');
  139. When output via ``toString()``, a text header produces something like the
  140. following:
  141. .. code-block:: php
  142. $subject = $message->getHeaders()->get('Subject');
  143. $subject->setValue('amazing subject line');
  144. echo $subject->toString();
  145. /*
  146. Subject: amazing subject line
  147. */
  148. If the header contains any characters that are outside of the US-ASCII range
  149. however, they will be encoded. This is nothing to be concerned about since
  150. mail clients will decode them back.
  151. .. code-block:: php
  152. $subject = $message->getHeaders()->get('Subject');
  153. $subject->setValue('contains – dash');
  154. echo $subject->toString();
  155. /*
  156. Subject: contains =?utf-8?Q?=E2=80=93?= dash
  157. */
  158. Parameterized Headers
  159. ~~~~~~~~~~~~~~~~~~~~~
  160. Parameterized headers are text headers that contain key-value parameters
  161. following the textual content. The Content-Type header of a message is a
  162. parameterized header since it contains charset information after the content
  163. type.
  164. The parameterized header type is a special type of text header. It extends the
  165. text header by allowing additional information to follow it. All of the methods
  166. from text headers are available in addition to the methods described here.
  167. Adding a parameterized header to a HeaderSet is done by using the
  168. ``addParameterizedHeader()`` method which takes a text value like
  169. ``addTextHeader()`` but it also accepts an associative array of
  170. key-value parameters.
  171. .. code-block:: php
  172. $message = Swift_Message::newInstance();
  173. $headers = $message->getHeaders();
  174. $headers->addParameterizedHeader(
  175. 'Header-Name', 'header value',
  176. array('foo' => 'bar')
  177. );
  178. To change the text value of the header, call it's ``setValue()`` method just as
  179. you do with text headers.
  180. To change the parameters in the header, call the header's ``setParameters()``
  181. method or the ``setParameter()`` method (note the pluralization).
  182. .. code-block:: php
  183. $type = $message->getHeaders()->get('Content-Type');
  184. // setParameters() takes an associative array
  185. $type->setParameters(array(
  186. 'name' => 'file.txt',
  187. 'charset' => 'iso-8859-1'
  188. ));
  189. // setParameter() takes two args for $key and $value
  190. $type->setParameter('charset', 'iso-8859-1');
  191. When output via ``toString()``, a parameterized header produces something like
  192. the following:
  193. .. code-block:: php
  194. $type = $message->getHeaders()->get('Content-Type');
  195. $type->setValue('text/html');
  196. $type->setParameter('charset', 'utf-8');
  197. echo $type->toString();
  198. /*
  199. Content-Type: text/html; charset=utf-8
  200. */
  201. If the header contains any characters that are outside of the US-ASCII range
  202. however, they will be encoded, just like they are for text headers. This is
  203. nothing to be concerned about since mail clients will decode them back.
  204. Likewise, if the parameters contain any non-ascii characters they will be
  205. encoded so that they can be transmitted safely.
  206. .. code-block:: php
  207. $attachment = Swift_Attachment::newInstance();
  208. $disp = $attachment->getHeaders()->get('Content-Disposition');
  209. $disp->setValue('attachment');
  210. $disp->setParameter('filename', 'report–may.pdf');
  211. echo $disp->toString();
  212. /*
  213. Content-Disposition: attachment; filename*=utf-8''report%E2%80%93may.pdf
  214. */
  215. Date Headers
  216. ~~~~~~~~~~~~
  217. Date headers contains an RFC 2822 formatted date (i.e. what PHP's ``date('r')``
  218. returns). They are used anywhere a date or time is needed to be presented as a
  219. message header.
  220. The data on which a date header is modeled is simply a UNIX timestamp such as
  221. that returned by ``time()`` or ``strtotime()``. The timestamp is used to create
  222. a correctly structured RFC 2822 formatted date such as
  223. ``Tue, 17 Feb 2009 22:26:31 +1100``.
  224. The obvious place this header type is used is in the ``Date:`` header of the
  225. message itself.
  226. It's easy to add a new date header to a HeaderSet. You do this by calling
  227. the HeaderSet's ``addDateHeader()`` method.
  228. .. code-block:: php
  229. $message = Swift_Message::newInstance();
  230. $headers = $message->getHeaders();
  231. $headers->addDateHeader('Your-Header-Name', strtotime('3 days ago'));
  232. Changing the value of an existing date header is done by calling it's
  233. ``setTimestamp()`` method.
  234. .. code-block:: php
  235. $date = $message->getHeaders()->get('Date');
  236. $date->setTimestamp(time());
  237. When output via ``toString()``, a date header produces something like the
  238. following:
  239. .. code-block:: php
  240. $date = $message->getHeaders()->get('Date');
  241. echo $date->toString();
  242. /*
  243. Date: Wed, 18 Feb 2009 13:35:02 +1100
  244. */
  245. Mailbox (e-mail address) Headers
  246. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  247. Mailbox headers contain one or more email addresses, possibly with
  248. personalized names attached to them. The data on which they are modeled is
  249. represented by an associative array of email addresses and names.
  250. Mailbox headers are probably the most complex header type to understand in
  251. Swift Mailer because they accept their input as an array which can take various
  252. forms, as described in the previous chapter.
  253. All of the headers that contain e-mail addresses in a message -- with the
  254. exception of ``Return-Path:`` which has a stricter syntax -- use this header
  255. type. That is, ``To:``, ``From:`` etc.
  256. You add a new mailbox header to a HeaderSet by calling the HeaderSet's
  257. ``addMailboxHeader()`` method.
  258. .. code-block:: php
  259. $message = Swift_Message::newInstance();
  260. $headers = $message->getHeaders();
  261. $headers->addMailboxHeader('Your-Header-Name', array(
  262. 'person1@example.org' => 'Person Name One',
  263. 'person2@example.org',
  264. 'person3@example.org',
  265. 'person4@example.org' => 'Another named person'
  266. ));
  267. Changing the value of an existing mailbox header is done by calling it's
  268. ``setNameAddresses()`` method.
  269. .. code-block:: php
  270. $to = $message->getHeaders()->get('To');
  271. $to->setNameAddresses(array(
  272. 'joe@example.org' => 'Joe Bloggs',
  273. 'john@example.org' => 'John Doe',
  274. 'no-name@example.org'
  275. ));
  276. If you don't wish to concern yourself with the complicated accepted input
  277. formats accepted by ``setNameAddresses()`` as described in the previous chapter
  278. and you only want to set one or more addresses (not names) then you can just
  279. use the ``setAddresses()`` method instead.
  280. .. code-block:: php
  281. $to = $message->getHeaders()->get('To');
  282. $to->setAddresses(array(
  283. 'joe@example.org',
  284. 'john@example.org',
  285. 'no-name@example.org'
  286. ));
  287. .. note::
  288. Both methods will accept the above input format in practice.
  289. If all you want to do is set a single address in the header, you can use a
  290. string as the input parameter to ``setAddresses()`` and/or
  291. ``setNameAddresses()``.
  292. .. code-block:: php
  293. $to = $message->getHeaders()->get('To');
  294. $to->setAddresses('joe-bloggs@example.org');
  295. When output via ``toString()``, a mailbox header produces something like the
  296. following:
  297. .. code-block:: php
  298. $to = $message->getHeaders()->get('To');
  299. $to->setNameAddresses(array(
  300. 'person1@example.org' => 'Name of Person',
  301. 'person2@example.org',
  302. 'person3@example.org' => 'Another Person'
  303. ));
  304. echo $to->toString();
  305. /*
  306. To: Name of Person <person1@example.org>, person2@example.org, Another Person
  307. <person3@example.org>
  308. */
  309. ID Headers
  310. ~~~~~~~~~~
  311. ID headers contain identifiers for the entity (or the message). The most
  312. notable ID header is the Message-ID header on the message itself.
  313. An ID that exists inside an ID header looks more-or-less less like an email
  314. address. For example, ``<![CDATA[<1234955437.499becad62ec2@example.org>]]>``.
  315. The part to the left of the @ sign is usually unique, based on the current time
  316. and some random factor. The part on the right is usually a domain name.
  317. Any ID passed the an ID header's ``setId()`` method absolutely MUST conform to
  318. this structure, otherwise you'll get an Exception thrown at you by Swift Mailer
  319. (a ``Swift_RfcComplianceException``). This is to ensure that the generated
  320. email complies with relevant RFC documents and therefore is less likely to be
  321. blocked as spam.
  322. It's easy to add a new ID header to a HeaderSet. You do this by calling
  323. the HeaderSet's ``addIdHeader()`` method.
  324. .. code-block:: php
  325. $message = Swift_Message::newInstance();
  326. $headers = $message->getHeaders();
  327. $headers->addIdHeader('Your-Header-Name', '123456.unqiue@example.org');
  328. Changing the value of an existing date header is done by calling its
  329. ``setId()`` method.
  330. .. code-block:: php
  331. $msgId = $message->getHeaders()->get('Message-ID');
  332. $msgId->setId(time() . '.' . uniqid('thing') . '@example.org');
  333. When output via ``toString()``, an ID header produces something like the
  334. following:
  335. .. code-block:: php
  336. $msgId = $message->getHeaders()->get('Message-ID');
  337. echo $msgId->toString();
  338. /*
  339. Message-ID: <1234955437.499becad62ec2@example.org>
  340. */
  341. Path Headers
  342. ~~~~~~~~~~~~
  343. Path headers are like very-restricted mailbox headers. They contain a single
  344. email address with no associated name. The Return-Path header of a message is
  345. a path header.
  346. You add a new path header to a HeaderSet by calling the HeaderSet's
  347. ``addPathHeader()`` method.
  348. .. code-block:: php
  349. $message = Swift_Message::newInstance();
  350. $headers = $message->getHeaders();
  351. $headers->addPathHeader('Your-Header-Name', 'person@example.org');
  352. Changing the value of an existing path header is done by calling its
  353. ``setAddress()`` method.
  354. .. code-block:: php
  355. $return = $message->getHeaders()->get('Return-Path');
  356. $return->setAddress('my-address@example.org');
  357. When output via ``toString()``, a path header produces something like the
  358. following:
  359. .. code-block:: php
  360. $return = $message->getHeaders()->get('Return-Path');
  361. $return->setAddress('person@example.org');
  362. echo $return->toString();
  363. /*
  364. Return-Path: <person@example.org>
  365. */
  366. Header Operations
  367. -----------------
  368. Working with the headers in a message involves knowing how to use the methods
  369. on the HeaderSet and on the individual Headers within the HeaderSet.
  370. Adding new Headers
  371. ~~~~~~~~~~~~~~~~~~
  372. New headers can be added to the HeaderSet by using one of the provided
  373. ``add..Header()`` methods.
  374. To add a header to a MIME entity (such as the message):
  375. Get the HeaderSet from the entity by via its ``getHeaders()`` method.
  376. * Add the header to the HeaderSet by calling one of the ``add..Header()``
  377. methods.
  378. The added header will appear in the message when it is sent.
  379. .. code-block:: php
  380. // Adding a custom header to a message
  381. $message = Swift_Message::newInstance();
  382. $headers = $message->getHeaders();
  383. $headers->addTextHeader('X-Mine', 'something here');
  384. // Adding a custom header to an attachment
  385. $attachment = Swift_Attachment::fromPath('/path/to/doc.pdf');
  386. $attachment->getHeaders()->addDateHeader('X-Created-Time', time());
  387. Retrieving Headers
  388. ~~~~~~~~~~~~~~~~~~
  389. Headers are retrieved through the HeaderSet's ``get()`` and ``getAll()``
  390. methods.
  391. To get a header, or several headers from a MIME entity:
  392. * Get the HeaderSet from the entity by via its ``getHeaders()`` method.
  393. * Get the header(s) from the HeaderSet by calling either ``get()`` or
  394. ``getAll()``.
  395. When using ``get()`` a single header is returned that matches the name (case
  396. insensitive) that is passed to it. When using ``getAll()`` with a header name,
  397. an array of headers with that name are returned. Calling ``getAll()`` with no
  398. arguments returns an array of all headers present in the entity.
  399. .. note::
  400. It's valid for some headers to appear more than once in a message (e.g.
  401. the Received header). For this reason ``getAll()`` exists to fetch all
  402. headers with a specified name. In addition, ``get()`` accepts an optional
  403. numerical index, starting from zero to specify which header you want more
  404. specifically.
  405. .. note::
  406. If you want to modify the contents of the header and you don't know for
  407. sure what type of header it is then you may need to check the type by
  408. calling its ``getFieldType()`` method.
  409. .. code-block:: php
  410. $headers = $message->getHeaders();
  411. // Get the To: header
  412. $toHeader = $headers->get('To');
  413. // Get all headers named "X-Foo"
  414. $fooHeaders = $headers->getAll('X-Foo');
  415. // Get the second header named "X-Foo"
  416. $foo = $headers->get('X-Foo', 1);
  417. // Get all headers that are present
  418. $all = $headers->getAll();
  419. Check if a Header Exists
  420. ~~~~~~~~~~~~~~~~~~~~~~~~
  421. You can check if a named header is present in a HeaderSet by calling its
  422. ``has()`` method.
  423. To check if a header exists:
  424. * Get the HeaderSet from the entity by via its ``getHeaders()`` method.
  425. * Call the HeaderSet's ``has()`` method specifying the header you're looking
  426. for.
  427. If the header exists, ``true`` will be returned or ``false`` if not.
  428. .. note::
  429. It's valid for some headers to appear more than once in a message (e.g.
  430. the Received header). For this reason ``has()`` accepts an optional
  431. numerical index, starting from zero to specify which header you want to
  432. check more specifically.
  433. .. code-block:: php
  434. $headers = $message->getHeaders();
  435. // Check if the To: header exists
  436. if ($headers->has('To')) {
  437. echo 'To: exists';
  438. }
  439. // Check if an X-Foo header exists twice (i.e. check for the 2nd one)
  440. if ($headers->has('X-Foo', 1)) {
  441. echo 'Second X-Foo header exists';
  442. }
  443. Removing Headers
  444. ~~~~~~~~~~~~~~~~
  445. Removing a Header from the HeaderSet is done by calling the HeaderSet's
  446. ``remove()`` or ``removeAll()`` methods.
  447. To remove an existing header:
  448. * Get the HeaderSet from the entity by via its ``getHeaders()`` method.
  449. * Call the HeaderSet's ``remove()`` or ``removeAll()`` methods specifying the
  450. header you want to remove.
  451. When calling ``remove()`` a single header will be removed. When calling
  452. ``removeAll()`` all headers with the given name will be removed. If no headers
  453. exist with the given name, no errors will occur.
  454. .. note::
  455. It's valid for some headers to appear more than once in a message (e.g.
  456. the Received header). For this reason ``remove()`` accepts an optional
  457. numerical index, starting from zero to specify which header you want to
  458. check more specifically. For the same reason, ``removeAll()`` exists to
  459. remove all headers that have the given name.
  460. .. code-block:: php
  461. $headers = $message->getHeaders();
  462. // Remove the Subject: header
  463. $headers->remove('Subject');
  464. // Remove all X-Foo headers
  465. $headers->removeAll('X-Foo');
  466. // Remove only the second X-Foo header
  467. $headers->remove('X-Foo', 1);
  468. Modifying a Header's Content
  469. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  470. To change a Header's content you should know what type of header it is and then
  471. call it's appropriate setter method. All headers also have a
  472. ``setFieldBodyModel()`` method that accepts a mixed parameter and delegates to
  473. the correct setter.
  474. To modify an existing header:
  475. * Get the HeaderSet from the entity by via its ``getHeaders()`` method.
  476. * Get the Header by using the HeaderSet's ``get()``.
  477. * Call the Header's appropriate setter method or call the header's
  478. ``setFieldBodyModel()`` method.
  479. The header will be updated inside the HeaderSet and the changes will be seen
  480. when the message is sent.
  481. .. code-block:: php
  482. $headers = $message->getHeaders();
  483. // Change the Subject: header
  484. $subj = $headers->get('Subject');
  485. $subj->setValue('new subject here');
  486. // Change the To: header
  487. $to = $headers->get('To');
  488. $to->setNameAddresses(array(
  489. 'person@example.org' => 'Person',
  490. 'thing@example.org'
  491. ));
  492. // Using the setFieldBodyModel() just delegates to the correct method
  493. // So here to calls setNameAddresses()
  494. $to->setFieldBodyModel(array(
  495. 'person@example.org' => 'Person',
  496. 'thing@example.org'
  497. ));