sending.rst 20KB

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