Spool Swiftmailer emails to real message queue.

Max Kotliar
formapro
Published in
2 min readAug 7, 2017

--

Swiftmailer is one of the most popular mailer library in PHP world. In general the library works pretty good though there is a case that could be improved and it is: email queueing. The email queuing come in handy in such situations:

  • The mail server is not available at the moment but it is very important to actually send emails.
  • There must be a way to retry sending if there was unexpected error or the processes died.
  • Align the load on servers.
  • Reduces web process time.

To summarize: email queueing improves overall performance and stability.

A short note: There are mail servers that support queuing at their side hence there is no need to maintain it at your side, so check the mail server doc before you roll up your sleeves and start digging into the code.

To get started let’s install some packages:

composer require swiftmailer/swiftmailer:^6 enqueue/fs

The solution is based on queue interop so you can choose any compatible transport.

The Swiftmailer has a notion of queues which they call spool. We have to create our own spool that is able to send messages to a queue and later flush them by sending to a real mail server. For that we have to create a class that implements \Swift_Spool interface.

The queue spool is ready and now we need to tie different parts together. First, we have to create a queue context with a help of a connection factory. Second, we have to create a spool transport which uses our queue spool.

At this stage, the email has not been sent for real, instead, it has been stored to a filesystem. To actually send them we need a consumer script that takes emails from the queue and sends them to the server:

If you prefer the Enqueue way of message consumption. Here’s the solution. It could be used in plain php as well as a framework such as Laravel and Symfony.

The 150 lines of code and 10 minutes of time and now you have a email queueing.

You can also visit our corporate blog to learn more about up-to-date IT trends and download some useful insights.

--

--