Symfony 4 was released on November 30th.
Update now to the best Symfony ever!

You are browsing the Symfony 4 documentation, which changes significantly from Symfony 3.x. If your app doesn't use Symfony 4 yet, browse the Symfony 3.4 documentation.

How to Send an Email

How to Send an Email

Symfony provides a mailer feature based on the popular Swift Mailer library via the SwiftMailerBundle. This mailer supports sending messages with your own mail servers as well as using popular email providers like Mandrill, SendGrid, and Amazon SES.

Installation

In applications using Symfony Flex, run this command to install the Swift Mailer based mailer before using it:

1
$ composer require mailer

If your application doesn't use Symfony Flex, follow the installation instructions on SwiftMailerBundle.

Configuration

The config/packages/swiftmailer.yaml file that's created when installing the mailer provides all the initial config needed to send emails, except your mail server connection details. Those parameters are defined in the MAILER_URL environment variable in the .env file:

1
2
3
4
5
# use this to disable email delivery
MAILER_URL=null://localhost

# use this to configure a traditional SMTP server
MAILER_URL=smtp://localhost:25?encryption=ssl&auth_mode=login&username=&password=

Refer to the SwiftMailer configuration reference for the detailed explanation of all the available config options.

Sending Emails

The Swift Mailer library works by creating, configuring and then sending Swift_Message objects. The "mailer" is responsible for the actual delivery of the message and is accessible via the Swift_Mailer service. Overall, sending an email is pretty straightforward:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public function indexAction($name, \Swift_Mailer $mailer)
{
    $message = (new \Swift_Message('Hello Email'))
        ->setFrom('send@example.com')
        ->setTo('recipient@example.com')
        ->setBody(
            $this->renderView(
                // templates/emails/registration.html.twig
                'emails/registration.html.twig',
                array('name' => $name)
            ),
            'text/html'
        )
        /*
         * If you also want to include a plaintext version of the message
        ->addPart(
            $this->renderView(
                'emails/registration.txt.twig',
                array('name' => $name)
            ),
            'text/plain'
        )
        */
    ;

    $mailer->send($message);

    return $this->render(...);
}

To keep things decoupled, the email body has been stored in a template and rendered with the renderView() method. The registration.html.twig template might look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
{# templates/emails/registration.html.twig #}
<h3>You did it! You registered!</h3>

Hi {{ name }}! You're successfully registered.

{# example, assuming you have a route named "login" #}
To login, go to: <a href="{{ url('login') }}">...</a>.

Thanks!

{# Makes an absolute URL to the /images/logo.png file #}
<img src="{{ absolute_url(asset('images/logo.png')) }}">

The $message object supports many more options, such as including attachments, adding HTML content, and much more. Refer to the Creating Messages section of the Swift Mailer documentation for more details.

Using Gmail to Send Emails

During development, you might prefer to send emails using Gmail instead of setting up a regular SMTP server. To do that, update the MAILER_URL of your .env file to this:

1
2
# username is your full Gmail or Google Apps email address
MAILER_URL=gmail://username:password@localhost

The gmail transport is simply a shortcut that uses the smtp transport, ssl encryption, login auth mode and smtp.gmail.com host. If your app uses other encryption or auth mode, you must override those values (see mailer config reference):

1
2
# username is your full Gmail or Google Apps email address
MAILER_URL=gmail://username:password@localhost?encryption=tls&auth_mode=oauth

If your Gmail account uses 2-Step-Verification, you must generate an App password and use it as the value of the mailer password. You must also ensure that you allow less secure apps to access your Gmail account.

Using Cloud Services to Send Emails

Cloud mailing services are a popular option for companies that don't want to set up and maintain their own reliable mail servers. In Symfony apps, using these services is as simple as updating the value of MAILER_URL in the .env file. For example, for Amazon SES (Simple Email Service):

1
2
3
# The host will be different depending on your AWS zone
# The username/password credentials are obtained from the Amazon SES console
MAILER_URL=smtp://email-smtp.us-east-1.amazonaws.com:587?encryption=tls&username=YOUR_SES_USERNAME&password=YOUR_SES_PASSWORD

Use the same technique for other mail services, as most of the time there is nothing more to it than configuring an SMTP endpoint.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.