w0-efa
Last Updated: February 25, 2016
·
7.673K
· zoltanradics
360

Symfony2 - Sending e-mails with SwiftMailer

If your application is sending e-mails to the users you will probably use SwiftMailer to do it.

First step is write the configuration file. In this example my local development environment use a gmail smtp and in the same time i would use the default server stmp settings on the production.

Your app/config/parameters.yml will look like this:

# Mail setup for development environment
dev_mailer_transport: gmail
dev_mailer_host: null
dev_mailer_user: example@gmail.com
dev_mailer_password: somepassword

# Mail setup for production environment
prod_mailer_transport: smtp
prod_mailer_host: localhost
prod_mailer_user: null    
prod_mailer_password: null

Now you have to modify your config_dev.yml file:

# Swiftmailer Configuration
swiftmailer:
    transport: %dev_mailer_transport%
    host:      %dev_mailer_host%
    username:  %dev_mailer_user%
    password:  %dev_mailer_password%
    spool:     { type: memory }

and your config_prod.yml as well:

# Swiftmailer Configuration
swiftmailer:
    transport: %prod_mailer_transport%
    host:      %prod_mailer_host%
    username:  %prod_mailer_user%
    password:  %prod_mailer_password%
    spool:     { type: memory }

Now you are able to send e-mails from your application. Here is an example for sending:

# Setup the message
$message = \Swift_Message::newInstance()
    ->setSubject('Some Subject')
    ->setFrom('example@gmail.com')
    ->setTo('any@whatever.com')
    ->setBody('ExampleBundle:Default:mail.html.twig', 'text/html');

# Send the message
$this->get('mailer')
    ->send($message);
Say Thanks
Respond