sending.rst 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. Sending Messages
  2. ================
  3. Quick Reference for Sending a Message
  4. -------------------------------------
  5. Sending a message is very straightforward. You create a Transport, use it to
  6. create the Mailer, then you use the Mailer to send the message.
  7. To send a Message:
  8. * Create a Transport from one of the provided Transports --
  9. ``Swift_SmtpTransport``, ``Swift_SendmailTransport``,
  10. ``Swift_MailTransport`` or one of the aggregate Transports.
  11. * Create an instance of the ``Swift_Mailer`` class, using the Transport as
  12. it's constructor parameter.
  13. * Create a Message.
  14. * Send the message via the ``send()`` method on the Mailer object.
  15. .. caution::
  16. The ``Swift_SmtpTransport`` and ``Swift_SendmailTransport`` transports use
  17. ``proc_*`` PHP functions, which might not be available on your PHP
  18. installation. You can easily check if that the case by running the
  19. following PHP script: ``<?php echo function_exists('proc_open') ? "Yep,
  20. that will work" : "Sorry, that won't work"; ``
  21. When using ``send()`` the message will be sent just like it would
  22. be sent if you used your mail client. An integer is returned which includes
  23. the number of successful recipients. If none of the recipients could be sent
  24. to then zero will be returned, which equates to a boolean
  25. ``false``. If you set two ``To:`` recipients and
  26. three ``Bcc:`` recipients in the message and all of the
  27. recipients are delivered to successfully then the value 5 will be returned.
  28. .. code-block:: php
  29. require_once 'lib/swift_required.php';
  30. //Create the Transport
  31. $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
  32. ->setUsername('your username')
  33. ->setPassword('your password')
  34. ;
  35. /*
  36. You could alternatively use a different transport such as Sendmail or Mail:
  37. //Sendmail
  38. $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
  39. //Mail
  40. $transport = Swift_MailTransport::newInstance();
  41. */
  42. //Create the Mailer using your created Transport
  43. $mailer = Swift_Mailer::newInstance($transport);
  44. //Create a message
  45. $message = Swift_Message::newInstance('Wonderful Subject')
  46. ->setFrom(array('john@doe.com' => 'John Doe'))
  47. ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
  48. ->setBody('Here is the message itself')
  49. ;
  50. //Send the message
  51. $result = $mailer->send($message);
  52. Transport Types
  53. ~~~~~~~~~~~~~~~
  54. A Transport is the component which actually does the sending. You need to
  55. provide a Transport object to the Mailer class and there are several possible
  56. options.
  57. Typically you will not need to know how a Transport works under-the-surface,
  58. you will only need to know how to create an instance of one, and which one to
  59. use for your environment.
  60. The SMTP Transport
  61. ..................
  62. The SMTP Transport sends messages over the (standardized) Simple Message Transfer
  63. Protocol. It can deal with encryption and authentication.
  64. The SMTP Transport, ``Swift_SmtpTransport`` is without doubt the most commonly
  65. used Transport because it will work on 99% of web servers (I just made that
  66. number up, but you get the idea). All the server needs is the ability to
  67. connect to a remote (or even local) SMTP server on the correct port number
  68. (usually 25).
  69. SMTP servers often require users to authenticate with a username and password
  70. before any mail can be sent to other domains. This is easily achieved using
  71. Swift Mailer with the SMTP Transport.
  72. SMTP is a protocol -- in other words it's a "way" of communicating a job
  73. to be done (i.e. sending a message). The SMTP protocol is the fundamental
  74. basis on which messages are delivered all over the internet 7 days a week, 365
  75. days a year. For this reason it's the most "direct" method of sending messages
  76. you can use and it's the one that will give you the most power and feedback
  77. (such as delivery failures) when using Swift Mailer.
  78. Because SMTP is generally run as a remote service (i.e. you connect to it over
  79. the network/internet) it's extremely portable from server-to-server. You can
  80. easily store the SMTP server address and port number in a configuration file
  81. within your application and adjust the settings accordingly if the code is
  82. moved or if the SMTP server is changed.
  83. Some SMTP servers -- Google for example -- use encryption for
  84. security reasons. Swift Mailer supports using both SSL and TLS encryption
  85. settings.
  86. Using the SMTP Transport
  87. ^^^^^^^^^^^^^^^^^^^^^^^^
  88. The SMTP Transport is easy to use. Most configuration options can be set with
  89. the constructor.
  90. To use the SMTP Transport you need to know which SMTP server your code needs
  91. to connect to. Ask your web host if you're not sure. Lots of people ask me who
  92. to connect to -- I really can't answer that since it's a setting that's
  93. extremely specific to your hosting environment.
  94. To use the SMTP Transport:
  95. * Call ``Swift_SmtpTransport::newInstance()`` with the SMTP server name and
  96. optionally with a port number (defaults to 25).
  97. * Use the returned object to create the Mailer.
  98. A connection to the SMTP server will be established upon the first call to
  99. ``send()``.
  100. .. code-block:: php
  101. require_once 'lib/swift_required.php';
  102. //Create the Transport
  103. $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25);
  104. //Create the Mailer using your created Transport
  105. $mailer = Swift_Mailer::newInstance($transport);
  106. /*
  107. It's also possible to use multiple method calls
  108. $transport = Swift_SmtpTransport::newInstance()
  109. ->setHost('smtp.example.org')
  110. ->setPort(25)
  111. ;
  112. */
  113. Encrypted SMTP
  114. ^^^^^^^^^^^^^^
  115. You can use SSL or TLS encryption with the SMTP Transport by specifying it as
  116. a parameter or with a method call.
  117. To use encryption with the SMTP Transport:
  118. * Pass the encryption setting as a third parameter to
  119. ``Swift_SmtpTransport::newInstance()``; or
  120. * Call the ``setEncryption()`` method on the Transport.
  121. A connection to the SMTP server will be established upon the first call to
  122. ``send()``. The connection will be initiated with the correct encryption
  123. settings.
  124. .. note::
  125. For SSL or TLS encryption to work your PHP installation must have
  126. appropriate OpenSSL transports wrappers. You can check if "tls" and/or
  127. "ssl" are present in your PHP installation by using the PHP function
  128. ``stream_get_transports()``
  129. .. code-block:: php
  130. require_once 'lib/swift_required.php';
  131. //Create the Transport
  132. $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 587, 'ssl');
  133. //Create the Mailer using your created Transport
  134. $mailer = Swift_Mailer::newInstance($transport);
  135. /*
  136. It's also possible to use multiple method calls
  137. $transport = Swift_SmtpTransport::newInstance()
  138. ->setHost('smtp.example.org')
  139. ->setPort(587)
  140. ->setEncryption('ssl')
  141. ;
  142. */
  143. SMTP with a Username and Password
  144. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  145. Some servers require authentication. You can provide a username and password
  146. with ``setUsername()`` and ``setPassword()``.
  147. To use a username and password with the SMTP Transport:
  148. * Create the Transport with ``Swift_SmtpTransport::newInstance()``.
  149. * Call the ``setUsername()`` and ``setPassword()`` methods on the Transport.
  150. Your username and password will be used to authenticate upon first connect
  151. when ``send()`` are first used on the Mailer.
  152. If authentication fails, an Exception of type
  153. ``Swift_TransportException`` will be thrown.
  154. .. note::
  155. If you need to know early whether or not authentication has failed and an
  156. Exception is going to be thrown, call the ``start()`` method on the
  157. created Transport.
  158. .. code-block:: php
  159. require_once 'lib/swift_required.php';
  160. //Create the Transport the call setUsername() and setPassword()
  161. $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
  162. ->setUsername('username')
  163. ->setPassword('password')
  164. ;
  165. //Create the Mailer using your created Transport
  166. $mailer = Swift_Mailer::newInstance($transport);
  167. The Sendmail Transport
  168. ......................
  169. The Sendmail Transport sends messages by communicating with a locally
  170. installed MTA -- such as ``sendmail``.
  171. The Sendmail Transport, ``Swift_SendmailTransport`` does not
  172. directly connect to any remote services. It is designed for Linux servers that
  173. have ``sendmail`` installed. The Transport starts a local
  174. ``sendmail`` process and sends messages to it. Usually the
  175. ``sendmail`` process will respond quickly as it spools your
  176. messages to disk before sending them.
  177. The Transport is named the Sendmail Transport for historical reasons
  178. (``sendmail`` was the "standard" UNIX tool for sending e-mail
  179. for years). It will send messages using other transfer agents such as Exim or
  180. Postfix despite its name, provided they have the relevant sendmail wrappers so
  181. that they can be started with the correct command-line flags.
  182. It's a common misconception that because the Sendmail Transport returns a
  183. result very quickly it must therefore deliver messages to recipients quickly
  184. -- this is not true. It's not slow by any means, but it's certainly not
  185. faster than SMTP when it comes to getting messages to the intended recipients.
  186. This is because sendmail itself sends the messages over SMTP once they have
  187. been quickly spooled to disk.
  188. The Sendmail Transport has the potential to be just as smart of the SMTP
  189. Transport when it comes to notifying Swift Mailer about which recipients were
  190. rejected, but in reality the majority of locally installed
  191. ``sendmail`` instances are not configured well enough to
  192. provide any useful feedback. As such Swift Mailer may report successful
  193. deliveries where they did in fact fail before they even left your server.
  194. You can run the Sendmail Transport in two different modes specified by command
  195. line flags:
  196. * "``-bs``" runs in SMTP mode so theoretically it will act like the SMTP
  197. Transport
  198. * "``-t``" runs in piped mode with no feedback, but theoretically faster,
  199. though not advised
  200. You can think of the Sendmail Transport as a sort of asynchronous SMTP
  201. Transport -- though if you have problems with delivery failures you
  202. should try using the SMTP Transport instead. Swift Mailer isn't doing the work
  203. here, it's simply passing the work to somebody else (i.e.
  204. ``sendmail``).
  205. Using the Sendmail Transport
  206. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  207. To use the Sendmail Transport you simply need to call
  208. ``Swift_SendmailTransport::newInstance()`` with the command as a
  209. parameter.
  210. To use the Sendmail Transport you need to know where
  211. ``sendmail`` or another MTA exists on the server. Swift Mailer
  212. uses a default value of ``/usr/sbin/sendmail``, which should
  213. work on most systems.
  214. You specify the entire command as a parameter (i.e. including the command line
  215. flags). Swift Mailer supports operational modes of "``-bs``"
  216. (default) and "``-t``".
  217. .. note::
  218. If you run sendmail in "``-t``" mode you will get no feedback as to
  219. whether or not sending has succeeded. Use "``-bs``" unless you have a
  220. reason not to.
  221. To use the Sendmail Transport:
  222. * Call ``Swift_SendmailTransport::newInstance()`` with the command, including
  223. the correct command line flags. The default is to use ``/usr/sbin/sendmail
  224. -bs`` if this is not specified.
  225. * Use the returned object to create the Mailer.
  226. A sendmail process will be started upon the first call to ``send()``. If the
  227. process cannot be started successfully an Exception of type
  228. ``Swift_TransportException`` will be thrown.
  229. .. code-block:: php
  230. require_once 'lib/swift_required.php';
  231. //Create the Transport
  232. $transport = Swift_SendmailTransport::newInstance('/usr/sbin/exim -bs');
  233. //Create the Mailer using your created Transport
  234. $mailer = Swift_Mailer::newInstance($transport);
  235. The Mail Transport
  236. ..................
  237. The Mail Transport sends messages by delegating to PHP's internal
  238. ``mail()`` function.
  239. In my experience -- and others' -- the ``mail()``
  240. function is not particularly predictable, or helpful.
  241. Quite notably, the ``mail()`` function behaves entirely
  242. differently between Linux and Windows servers. On linux it uses
  243. ``sendmail``, but on Windows it uses SMTP.
  244. In order for the ``mail()`` function to even work at all
  245. ``php.ini`` needs to be configured correctly, specifying the
  246. location of sendmail or of an SMTP server.
  247. The problem with ``mail()`` is that it "tries" to simplify things
  248. to the point that it actually makes things more complex due to poor interface
  249. design. The developers of Swift Mailer have gone to a lot of effort to make
  250. the Mail Transport work with a reasonable degree of consistency.
  251. Serious drawbacks when using this Transport are:
  252. * Unpredictable message headers
  253. * Lack of feedback regarding delivery failures
  254. * Lack of support for several plugins that require real-time delivery feedback
  255. It's a last resort, and we say that with a passion!
  256. Using the Mail Transport
  257. ^^^^^^^^^^^^^^^^^^^^^^^^
  258. To use the Mail Transport you simply need to call
  259. ``Swift_MailTransport::newInstance()``. It's unlikely you'll need
  260. to configure the Transport.
  261. To use the Mail Transport:
  262. * Call ``Swift_MailTransport::newInstance()``.
  263. * Use the returned object to create the Mailer.
  264. Messages will be sent using the ``mail()`` function.
  265. .. note::
  266. The ``mail()`` function can take a ``$additional_parameters`` parameter.
  267. Swift Mailer sets this to "``-f%s``" by default, where the "%s" is
  268. substituted with the address of the sender (via a ``sprintf()``) at send
  269. time. You may override this default by passing an argument to
  270. ``newInstance()``.
  271. .. code-block:: php
  272. require_once 'lib/swift_required.php';
  273. //Create the Transport
  274. $transport = Swift_MailTransport::newInstance();
  275. //Create the Mailer using your created Transport
  276. $mailer = Swift_Mailer::newInstance($transport);
  277. Available Methods for Sending Messages
  278. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  279. The Mailer class offers two methods for sending Messages -- ``send()``.
  280. Each behaves in a slightly different way.
  281. When a message is sent in Swift Mailer, the Mailer class communicates with
  282. whichever Transport class you have chosen to use.
  283. Each recipient in the message should either be accepted or rejected by the
  284. Transport. For example, if the domain name on the email address is not
  285. reachable the SMTP Transport may reject the address because it cannot process
  286. it. Whichever method you use -- ``send()`` -- Swift Mailer will return
  287. an integer indicating the number of accepted recipients.
  288. .. note::
  289. It's possible to find out which recipients were rejected -- we'll
  290. cover that later in this chapter.
  291. Using the ``send()`` Method
  292. ...........................
  293. The ``send()`` method of the ``Swift_Mailer`` class
  294. sends a message using exactly the same logic as your Desktop mail client would
  295. use. Just pass it a Message and get a result.
  296. To send a Message with ``send()``:
  297. * Create a Transport from one of the provided Transports --
  298. ``Swift_SmtpTransport``, ``Swift_SendmailTransport``,
  299. ``Swift_MailTransport`` or one of the aggregate Transports.
  300. * Create an instance of the ``Swift_Mailer`` class, using the Transport as
  301. it's constructor parameter.
  302. * Create a Message.
  303. * Send the message via the ``send()`` method on the Mailer object.
  304. The message will be sent just like it would be sent if you used your mail
  305. client. An integer is returned which includes the number of successful
  306. recipients. If none of the recipients could be sent to then zero will be
  307. returned, which equates to a boolean ``false``. If you set two
  308. ``To:`` recipients and three ``Bcc:`` recipients in
  309. the message and all of the recipients are delivered to successfully then the
  310. value 5 will be returned.
  311. .. code-block:: php
  312. require_once 'lib/swift_required.php';
  313. //Create the Transport
  314. $transport = Swift_SmtpTransport::newInstance('localhost', 25);
  315. //Create the Mailer using your created Transport
  316. $mailer = Swift_Mailer::newInstance($transport);
  317. //Create a message
  318. $message = Swift_Message::newInstance('Wonderful Subject')
  319. ->setFrom(array('john@doe.com' => 'John Doe'))
  320. ->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
  321. ->setBody('Here is the message itself')
  322. ;
  323. //Send the message
  324. $numSent = $mailer->send($message);
  325. printf("Sent %d messages\n", $numSent);
  326. /* Note that often that only the boolean equivalent of the
  327. return value is of concern (zero indicates FALSE)
  328. if ($mailer->send($message))
  329. {
  330. echo "Sent\n";
  331. }
  332. else
  333. {
  334. echo "Failed\n";
  335. }
  336. */
  337. Sending Emails in Batch
  338. .......................
  339. If you want to send a separate message to each recipient so that only their
  340. own address shows up in the ``To:`` field, follow the following recipe:
  341. * Create a Transport from one of the provided Transports --
  342. ``Swift_SmtpTransport``, ``Swift_SendmailTransport``,
  343. ``Swift_MailTransport`` or one of the aggregate Transports.
  344. * Create an instance of the ``Swift_Mailer`` class, using the Transport as
  345. it's constructor parameter.
  346. * Create a Message.
  347. * Iterate over the recipients and send message via the ``send()`` method on
  348. the Mailer object.
  349. Each recipient of the messages receives a different copy with only their own
  350. email address on the ``To:`` field.
  351. .. note::
  352. In the following example, two emails are sent. One to each of
  353. ``receiver@domain.org`` and ``other@domain.org``. These recipients will
  354. not be aware of each other.
  355. .. code-block:: php
  356. require_once 'lib/swift_required.php';
  357. //Create the Transport
  358. $transport = Swift_SmtpTransport::newInstance('localhost', 25);
  359. //Create the Mailer using your created Transport
  360. $mailer = Swift_Mailer::newInstance($transport);
  361. //Create a message
  362. $message = Swift_Message::newInstance('Wonderful Subject')
  363. ->setFrom(array('john@doe.com' => 'John Doe'))
  364. ->setBody('Here is the message itself')
  365. ;
  366. //Send the message
  367. $failedRecipients = array();
  368. $numSent = 0;
  369. $to = array('receiver@domain.org', 'other@domain.org' => 'A name');
  370. foreach ($to as $address => $name)
  371. {
  372. if (is_int($address)) {
  373. $message->setTo($name);
  374. } else {
  375. $message->setTo(array($address => $name));
  376. }
  377. $numSent += $mailer->send($message, $failedRecipients);
  378. }
  379. printf("Sent %d messages\n", $numSent);
  380. Finding out Rejected Addresses
  381. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  382. It's possible to get a list of addresses that were rejected by the Transport
  383. by using a by-reference parameter to ``send()``.
  384. As Swift Mailer attempts to send the message to each address given to it, if a
  385. recipient is rejected it will be added to the array. You can pass an existing
  386. array, otherwise one will be created by-reference.
  387. Collecting the list of recipients that were rejected can be useful in
  388. circumstances where you need to "prune" a mailing list for example when some
  389. addresses cannot be delivered to.
  390. Getting Failures By-reference
  391. .............................
  392. Collecting delivery failures by-reference with the ``send()`` method is as
  393. simple as passing a variable name to the method call.
  394. To get failed recipients by-reference:
  395. * Pass a by-reference variable name to the ``send()`` method of the Mailer
  396. class.
  397. If the Transport rejects any of the recipients, the culprit addresses will be
  398. added to the array provided by-reference.
  399. .. note::
  400. If the variable name does not yet exist, it will be initialized as an
  401. empty array and then failures will be added to that array. If the variable
  402. already exists it will be type-cast to an array and failures will be added
  403. to it.
  404. .. code-block:: php
  405. $mailer = Swift_Mailer::newInstance( ... );
  406. $message = Swift_Message::newInstance( ... )
  407. ->setFrom( ... )
  408. ->setTo(array(
  409. 'receiver@bad-domain.org' => 'Receiver Name',
  410. 'other@domain.org' => 'A name',
  411. 'other-receiver@bad-domain.org' => 'Other Name'
  412. ))
  413. ->setBody( ... )
  414. ;
  415. //Pass a variable name to the send() method
  416. if (!$mailer->send($message, $failures))
  417. {
  418. echo "Failures:";
  419. print_r($failures);
  420. }
  421. /*
  422. Failures:
  423. Array (
  424. 0 => receiver@bad-domain.org,
  425. 1 => other-receiver@bad-domain.org
  426. )
  427. */