sending.rst 20KB

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