Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages in full color showing how to combine Symfony with Docker, APIs, queues & async tasks, Webpack, Single-Page Applications, etc.

Buy printed version
WARNING: You are browsing the documentation for Symfony 3.0 which is not maintained anymore. Consider upgrading your projects to Symfony 5.1.

How to Test that an Email is Sent in a Functional Test

3.0 version
Maintained Unmaintained

How to Test that an Email is Sent in a Functional Test

Sending emails with Symfony is pretty straightforward thanks to the SwiftmailerBundle, which leverages the power of the Swift Mailer library.

To functionally test that an email was sent, and even assert the email subject, content or any other headers, you can use the Symfony Profiler.

Start with an easy controller action that sends an email:

public function sendEmailAction($name)
    $message = \Swift_Message::newInstance()
        ->setSubject('Hello Email')
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setBody('You should see me from the profiler!')


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


Don’t forget to enable the profiler as explained in How to Use the Profiler in a Functional Test.

In your functional test, use the swiftmailer collector on the profiler to get information about the messages sent on the previous request:

// tests/AppBundle/Controller/MailControllerTest.php
namespace Tests\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class MailControllerTest extends WebTestCase
    public function testMailIsSentAndContentIsOk()
        $client = static::createClient();

        // Enable the profiler for the next request (it does nothing if the profiler is not available)

        $crawler = $client->request('POST', '/path/to/above/action');

        $mailCollector = $client->getProfile()->getCollector('swiftmailer');

        // Check that an email was sent
        $this->assertEquals(1, $mailCollector->getMessageCount());

        $collectedMessages = $mailCollector->getMessages();
        $message = $collectedMessages[0];

        // Asserting email data
        $this->assertInstanceOf('Swift_Message', $message);
        $this->assertEquals('Hello Email', $message->getSubject());
        $this->assertEquals('[email protected]', key($message->getFrom()));
        $this->assertEquals('[email protected]', key($message->getTo()));
            'You should see me from the profiler!',

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