Setting up swiftmailer in Symfony2

Sure, swiftmailer already comes pre configured when you install symfony2.

However, it doesn’t really work out of the box, I mean, if we just make some code to send an email no email is sent…

The idea is that swiftmailer is configured by default in such a way as to save the emails it should send but not send them. This actually makes sense: when the user makes a request that requires an email to be sent, we don’t want our user to be waiting for the request response to arrive back to the browser while the email is sent. The request can return immediately, and the email can be sent later, after the request has been replied to.

The problem is that for the emails to be sent later, something has to start that process. Usually a cron job that makes the application send all the emails in the buffer.

So first we have to configure the mailer options in parameters.yml. In this case we set it up to use php mail() function:


## parameters.yml

mailer_transport: mail
mailer_host: localhost
mailer_user: null
mailer_password: null

Then we have to really configure swiftmailer. We will configure two mailers, one that sends emails immediately, ideally for CLI usage, and another one that puts the emails in the buffer, ideally for HTTP requests.
To use swiftmailer, we just need to get the service. If we want to use the default mailer we just call the mailer service ‘mailer’, if we want a specific mailer we call it explicitly as ie ‘swiftmailer.mailer.send_immediately’.


## config.yml

# Swiftmailer Configuration
# get the default with: $mailer = $this->get('mailer');
# get a specific mailer with: $mailer = $this->get('swiftmailer.mailer.send_later');
# get a specific mailer with: $mailer = $this->get('swiftmailer.mailer.send_immediately');
swiftmailer:
    default_mailer: send_immediately
    mailers:
    # for http requests:
    send_later:
        transport: %mailer_transport%
        host: %mailer_host%
        username: %mailer_user%
        password: %mailer_password%
        spool: { type: memory } # we need to have a cronjob to send emails in the buffer
    # for cli requests:
    send_immediately:
        transport: %mailer_transport%
        host: %mailer_host%
        username: %mailer_user%
        password: %mailer_password%

To send the emails in the buffer we run a symfony console command, which we obviously should put in a cron job:

php app/console swiftmailer:spool:send --env=prod
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s