PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

ReStructuredText | 385 lines | 274 code | 111 blank | 0 comment | 0 complexity | a4835182f93fb429c251a91704d908a3 MD5 | raw file
  1. Plugins
  2. =======
  3. Plugins are provided with Swift Mailer and can be used to extend the behavior
  4. of the library in situations where using simple class inheritance would be more complex.
  5. AntiFlood Plugin
  6. ----------------
  7. Many SMTP servers have limits on the number of messages that may be sent
  8. during any single SMTP connection. The AntiFlood plugin provides a way to stay
  9. within this limit while still managing a large number of emails.
  10. A typical limit for a single connection is 100 emails. If the server you
  11. connect to imposes such a limit, it expects you to disconnect after that
  12. number of emails has been sent. You could manage this manually within a loop,
  13. but the AntiFlood plugin provides the necessary wrapper code so that you don't
  14. need to worry about this logic.
  15. Regardless of limits imposed by the server, it's usually a good idea to be
  16. conservative with the resources of the SMTP server. Sending will become
  17. sluggish if the server is being over-used so using the AntiFlood plugin will
  18. not be a bad idea even if no limits exist.
  19. The AntiFlood plugin's logic is basically to disconnect and the immediately
  20. re-connect with the SMTP server every X number of emails sent, where X is a
  21. number you specify to the plugin.
  22. You can also specify a time period in seconds that Swift Mailer should pause
  23. for between the disconnect/re-connect process. It's a good idea to pause for a
  24. short time (say 30 seconds every 100 emails) simply to give the SMTP server a
  25. chance to process its queue and recover some resources.
  26. Using the AntiFlood Plugin
  27. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  28. The AntiFlood Plugin -- like all plugins -- is added with the Mailer class's
  29. ``registerPlugin()`` method. It takes two constructor parameters: the number of
  30. emails to pause after, and optionally the number of seconds to pause for.
  31. To use the AntiFlood plugin:
  32. * Create an instance of the Mailer using any Transport you choose.
  33. * Create an instance of the ``Swift_Plugins_AntiFloodPlugin`` class, passing
  34. in one or two constructor parameters.
  35. * Register the plugin using the Mailer's ``registerPlugin()`` method.
  36. * Continue using Swift Mailer to send messages as normal.
  37. When Swift Mailer sends messages it will count the number of messages that
  38. have been sent since the last re-connect. Once the number hits your specified
  39. threshold it will disconnect and re-connect, optionally pausing for a
  40. specified amount of time.
  41. .. code-block:: php
  42. require_once 'lib/swift_required.php';
  43. // Create the Mailer using any Transport
  44. $mailer = Swift_Mailer::newInstance(
  45. Swift_SmtpTransport::newInstance('', 25)
  46. );
  47. // Use AntiFlood to re-connect after 100 emails
  48. $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100));
  49. // And specify a time in seconds to pause for (30 secs)
  50. $mailer->registerPlugin(new Swift_Plugins_AntiFloodPlugin(100, 30));
  51. // Continue sending as normal
  52. for ($lotsOfRecipients as $recipient) {
  53. ...
  54. $mailer->send( ... );
  55. }
  56. Throttler Plugin
  57. ----------------
  58. If your SMTP server has restrictions in place to limit the rate at which you
  59. send emails, then your code will need to be aware of this rate-limiting. The
  60. Throttler plugin makes Swift Mailer run at a rate-limited speed.
  61. Many shared hosts don't open their SMTP servers as a free-for-all. Usually
  62. they have policies in place (probably to discourage spammers) that only allow
  63. you to send a fixed number of emails per-hour/day.
  64. The Throttler plugin supports two modes of rate-limiting and with each, you
  65. will need to do that math to figure out the values you want. The plugin can
  66. limit based on the number of emails per minute, or the number of
  67. bytes-transferred per-minute.
  68. Using the Throttler Plugin
  69. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  70. The Throttler Plugin -- like all plugins -- is added with the Mailer class'
  71. ``registerPlugin()`` method. It has two required constructor parameters that
  72. tell it how to do its rate-limiting.
  73. To use the Throttler plugin:
  74. * Create an instance of the Mailer using any Transport you choose.
  75. * Create an instance of the ``Swift_Plugins_ThrottlerPlugin`` class, passing
  76. the number of emails, or bytes you wish to limit by, along with the mode
  77. you're using.
  78. * Register the plugin using the Mailer's ``registerPlugin()`` method.
  79. * Continue using Swift Mailer to send messages as normal.
  80. When Swift Mailer sends messages it will keep track of the rate at which sending
  81. messages is occurring. If it realises that sending is happening too fast, it
  82. will cause your program to ``sleep()`` for enough time to average out the rate.
  83. .. code-block:: php
  84. require_once 'lib/swift_required.php';
  85. // Create the Mailer using any Transport
  86. $mailer = Swift_Mailer::newInstance(
  87. Swift_SmtpTransport::newInstance('', 25)
  88. );
  89. // Rate limit to 100 emails per-minute
  90. $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
  91. 100, Swift_Plugins_ThrottlerPlugin::MESSAGES_PER_MINUTE
  92. ));
  93. // Rate limit to 10MB per-minute
  94. $mailer->registerPlugin(new Swift_Plugins_ThrottlerPlugin(
  95. 1024 * 1024 * 10, Swift_Plugins_ThrottlerPlugin::BYTES_PER_MINUTE
  96. ));
  97. // Continue sending as normal
  98. for ($lotsOfRecipients as $recipient) {
  99. ...
  100. $mailer->send( ... );
  101. }
  102. Logger Plugin
  103. -------------
  104. The Logger plugins helps with debugging during the process of sending. It can
  105. help to identify why an SMTP server is rejecting addresses, or any other
  106. hard-to-find problems that may arise.
  107. The Logger plugin comes in two parts. There's the plugin itself, along with
  108. one of a number of possible Loggers that you may choose to use. For example,
  109. the logger may output messages directly in realtime, or it may capture
  110. messages in an array.
  111. One other notable feature is the way in which the Logger plugin changes
  112. Exception messages. If Exceptions are being thrown but the error message does
  113. not provide conclusive information as to the source of the problem (such as an
  114. ambiguous SMTP error) the Logger plugin includes the entire SMTP transcript in
  115. the error message so that debugging becomes a simpler task.
  116. There are a few available Loggers included with Swift Mailer, but writing your
  117. own implementation is incredibly simple and is achieved by creating a short
  118. class that implements the ``Swift_Plugins_Logger`` interface.
  119. * ``Swift_Plugins_Loggers_ArrayLogger``: Keeps a collection of log messages
  120. inside an array. The array content can be cleared or dumped out to the
  121. screen.
  122. * ``Swift_Plugins_Loggers_EchoLogger``: Prints output to the screen in
  123. realtime. Handy for very rudimentary debug output.
  124. Using the Logger Plugin
  125. ~~~~~~~~~~~~~~~~~~~~~~~
  126. The Logger Plugin -- like all plugins -- is added with the Mailer class'
  127. ``registerPlugin()`` method. It accepts an instance of ``Swift_Plugins_Logger``
  128. in its constructor.
  129. To use the Logger plugin:
  130. * Create an instance of the Mailer using any Transport you choose.
  131. * Create an instance of the a Logger implementation of
  132. ``Swift_Plugins_Logger``.
  133. * Create an instance of the ``Swift_Plugins_LoggerPlugin`` class, passing the
  134. created Logger instance to its constructor.
  135. * Register the plugin using the Mailer's ``registerPlugin()`` method.
  136. * Continue using Swift Mailer to send messages as normal.
  137. * Dump the contents of the log with the logger's ``dump()`` method.
  138. When Swift Mailer sends messages it will keep a log of all the interactions
  139. with the underlying Transport being used. Depending upon the Logger that has
  140. been used the behaviour will differ, but all implementations offer a way to
  141. get the contents of the log.
  142. .. code-block:: php
  143. require_once 'lib/swift_required.php';
  144. // Create the Mailer using any Transport
  145. $mailer = Swift_Mailer::newInstance(
  146. Swift_SmtpTransport::newInstance('', 25)
  147. );
  148. // To use the ArrayLogger
  149. $logger = new Swift_Plugins_Loggers_ArrayLogger();
  150. $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
  151. // Or to use the Echo Logger
  152. $logger = new Swift_Plugins_Loggers_EchoLogger();
  153. $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
  154. // Continue sending as normal
  155. for ($lotsOfRecipients as $recipient) {
  156. ...
  157. $mailer->send( ... );
  158. }
  159. // Dump the log contents
  160. // NOTE: The EchoLogger dumps in realtime so dump() does nothing for it
  161. echo $logger->dump();
  162. Decorator Plugin
  163. ----------------
  164. Often there's a need to send the same message to multiple recipients, but with
  165. tiny variations such as the recipient's name being used inside the message
  166. body. The Decorator plugin aims to provide a solution for allowing these small
  167. differences.
  168. The decorator plugin works by intercepting the sending process of Swift
  169. Mailer, reading the email address in the To: field and then looking up a set
  170. of replacements for a template.
  171. While the use of this plugin is simple, it is probably the most commonly
  172. misunderstood plugin due to the way in which it works. The typical mistake
  173. users make is to try registering the plugin multiple times (once for each
  174. recipient) -- inside a loop for example. This is incorrect.
  175. The Decorator plugin should be registered just once, but containing the list
  176. of all recipients prior to sending. It will use this list of recipients to
  177. find the required replacements during sending.
  178. Using the Decorator Plugin
  179. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  180. To use the Decorator plugin, simply create an associative array of replacements
  181. based on email addresses and then use the mailer's ``registerPlugin()`` method
  182. to add the plugin.
  183. First create an associative array of replacements based on the email addresses
  184. you'll be sending the message to.
  185. .. note::
  186. The replacements array becomes a 2-dimensional array whose keys are the
  187. email addresses and whose values are an associative array of replacements
  188. for that email address. The curly braces used in this example can be any
  189. type of syntax you choose, provided they match the placeholders in your
  190. email template.
  191. .. code-block:: php
  192. $replacements = array();
  193. foreach ($users as $user) {
  194. $replacements[$user['email']] = array(
  195. '{username}'=>$user['username'],
  196. '{password}'=>$user['password']
  197. );
  198. }
  199. Now create an instance of the Decorator plugin using this array of replacements
  200. and then register it with the Mailer. Do this only once!
  201. .. code-block:: php
  202. $decorator = new Swift_Plugins_DecoratorPlugin($replacements);
  203. $mailer->registerPlugin($decorator);
  204. When you create your message, replace elements in the body (and/or the subject
  205. line) with your placeholders.
  206. .. code-block:: php
  207. $message = Swift_Message::newInstance()
  208. ->setSubject('Important notice for {username}')
  209. ->setBody(
  210. "Hello {username}, we have reset your password to {password}\n" .
  211. "Please log in and change it at your earliest convenience."
  212. )
  213. ;
  214. foreach ($users as $user) {
  215. $message->addTo($user['email']);
  216. }
  217. When you send this message to each of your recipients listed in your
  218. ``$replacements`` array they will receive a message customized for just
  219. themselves. For example, the message used above when received may appear like
  220. this to one user:
  221. .. code-block:: text
  222. Subject: Important notice for smilingsunshine2009
  223. Hello smilingsunshine2009, we have reset your password to rainyDays
  224. Please log in and change it at your earliest convenience.
  225. While another use may receive the message as:
  226. .. code-block:: text
  227. Subject: Important notice for billy-bo-bob
  228. Hello billy-bo-bob, we have reset your password to dancingOctopus
  229. Please log in and change it at your earliest convenience.
  230. While the decorator plugin provides a means to solve this problem, there are
  231. various ways you could tackle this problem without the need for a plugin.
  232. We're trying to come up with a better way ourselves and while we have several
  233. (obvious) ideas we don't quite have the perfect solution to go ahead and
  234. implement it. Watch this space.
  235. Providing Your Own Replacements Lookup for the Decorator
  236. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  237. Filling an array with replacements may not be the best solution for providing
  238. replacement information to the decorator. If you have a more elegant algorithm
  239. that performs replacement lookups on-the-fly you may provide your own
  240. implementation.
  241. Providing your own replacements lookup implementation for the Decorator is
  242. simply a matter of passing an instance of ``Swift_Plugins_Decorator_Replacements`` to the decorator plugin's constructor,
  243. rather than passing in an array.
  244. The Replacements interface is very simple to implement since it has just one
  245. method: ``getReplacementsFor($address)``.
  246. Imagine you want to look up replacements from a database on-the-fly, you might
  247. provide an implementation that does this. You need to create a small class.
  248. .. code-block:: php
  249. class DbReplacements implements Swift_Plugins_Decorator_Replacements {
  250. public function getReplacementsFor($address) {
  251. $sql = sprintf(
  252. "SELECT * FROM user WHERE email = '%s'",
  253. mysql_real_escape_string($address)
  254. );
  255. $result = mysql_query($sql);
  256. if ($row = mysql_fetch_assoc($result)) {
  257. return array(
  258. '{username}'=>$row['username'],
  259. '{password}'=>$row['password']
  260. );
  261. }
  262. }
  263. }
  264. Now all you need to do is pass an instance of your class into the Decorator
  265. plugin's constructor instead of passing an array.
  266. .. code-block:: php
  267. $decorator = new Swift_Plugins_DecoratorPlugin(new DbReplacements());
  268. $mailer->registerPlugin($decorator);
  269. For each message sent, the plugin will call your class' ``getReplacementsFor()``
  270. method to find the array of replacements it needs.
  271. .. note::
  272. If your lookup algorithm is case sensitive, you should transform the
  273. ``$address`` argument as appropriate -- for example by passing it
  274. through ``strtolower()``.