Send emails with Symfony and Mandrill

To send emails, I use Mandrill which is a service by MailChimp. It is a very useful (and powerful) tool which provide you with a smtp server for free until 12k emails / month and a very well designed dashboard.

Price are quite cheap when you need more:

In my Symfony install, I needed to send many emails. So I discovered that a nice bundle exists (isn’t it surprising?). So here is my way to proceed:
– I downloaded Hip\MandrillBundle
– I created a service that send emails
– I call this service everytime I need to send an email

As a source worth a thousands words, let’s code:

<!--?php namespace Acme\XXXBundle\Services; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\HttpFoundation\Response; use Hip\MandrillBundle\Message; use Hip\MandrillBundle\Dispatcher; class EmailService {     private $container;     private $user;     /**     * We need the container to get the current user and the templateEngine     */     public function __construct(ContainerInterface $container)     {         $this--->user = $container-&gt;get('security.context')-&gt;getToken()-&gt;getUser();
        * I dont want to send emails if no one is logged
        $this-&gt;container = $container;
    * Send emails but need the subject and the content
    * If the destination is not set, it will be th current user
    private function send($dest, $subject, $content) {
        $dispatcher = $this-&gt;container-&gt;get('hip_mandrill.dispatcher');
        $message = new Message();
        if($dest == null)
            $dest = $this-&gt;user-&gt;getEmail();
         * Can add options such as:
         * -&gt;setFromEmail('')
         * -&gt;setFromName('Customer Care')
        $result = $dispatcher-&gt;send($message);
        return new Response('
' . print_r($result, true) . '



* Render the template and use it as html body
public function welcome() {
return $this->send(null, ‘My Title’,$html);

The service.yml:
        class: ACME\XXXBundle\Services\EmailService
        arguments: [@service_container]

Inside your controller:

        $emailService = $this->container->get('');
        return $emailService->welcome();

I will add a configuration point. Obviously, don’t forget to change mailer_* settings in parameters.yml with the one you will find in Mandrill. In your paramaters.yml, add mailer_port and “port: %mailer_port%” under swiftmailer in your config.yml

Here we are. You can now send emails easily for free to anyone.

If you read French, I recommend this article which was useful:

Leave a Reply

Your email address will not be published. Required fields are marked *