Send mails in Symfony in a way that does not suck!

I don’t like the approach the Symfony documentation suggests how to send mails in Symfony:

From my point of view, there are several drawbacks:

  • You have to put different parts for creating the mail in different places (i.E. “subject”,  “from” and “to” where the Swift_Message object is instantiated, both the body contents in two different files in the filesystem)
  • There ist no preferred way of defining messages with different locales (should they be translated with the Symfony translation component? Should there be one file for each locale of “text body” and “html body” like and
  • You have much boilerplate code for instantiating the Swift_Message object, because mostly mails are send from the same sender (from address)
  • There is no predefined location to store emails, basically you could put them everywhere, developers are not forced to put them at one place
  • You don’t want to be aware of the implementation of the underlaying mailer
  • 20 lines of code in your controller only for sending a stupid mail?

To address those points, I created a small bundle called HautziSystemMailBundle:

With this bundle, it is very simple to define your system-mails in an xml structure like this:

and with the help of twig, everything gets really powerful:

to send out those mail-definitions, your controller now looks like this:

Of course – in a DDD world, you should not send emails within an controller by default, but this blog post is only for demonstrating the capabilities of this bundle.

If you like this approach, you can find further information about its installation or some more examples on the github page of this bundle.

Feedback welcome :)