Step 20: Emailing Admins

Emailing Admins

First, install the Symfony Mailer component:

To store the admin email, use a container parameter. For demonstration purpose, we also allow it to be set via an environment variable (should not be needed in “real life”). To ease injection in services that need the admin email, define a container bind setting:

patch_file

  1. --- a/config/services.yaml
  2. +++ b/config/services.yaml
  3. @@ -4,6 +4,7 @@
  4. # Put parameters here that don't need to change on each machine where the app is deployed
  5. # https://symfony.com/doc/current/best_practices/configuration.html#application-related-configuration
  6. parameters:
  7. + default_admin_email:
  8. services:
  9. # default configuration for services in *this* file
  10. @@ -13,6 +14,7 @@ services:
  11. bind:
  12. $photoDir: "%kernel.project_dir%/public/uploads/photos"
  13. $akismetKey: "%env(AKISMET_KEY)%"
  14. + $adminEmail: "%env(string:default:default_admin_email:ADMIN_EMAIL)%"
  15. # makes classes in src/ available to be used as services
  16. # this creates a service per class whose id is the fully-qualified class name

An environment variable might be “processed” before being used. Here, we are using the default processor to fall back to the value of the default_admin_email parameter if the ADMIN_EMAIL environment variable does not exist.

Sending a Notification Email

To send an email, you can choose between several Email class abstractions; from Message, the lowest level, to NotificationEmail, the highest one. You will probably use the Email class the most, but NotificationEmail is the perfect choice for internal emails.

In the message handler, let’s replace the auto-validation logic:

patch_file

  1. --- a/src/MessageHandler/CommentMessageHandler.php
  2. +++ b/src/MessageHandler/CommentMessageHandler.php
  3. @@ -7,6 +7,8 @@ use App\Repository\CommentRepository;
  4. use App\SpamChecker;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Psr\Log\LoggerInterface;
  7. +use Symfony\Bridge\Twig\Mime\NotificationEmail;
  8. +use Symfony\Component\Mailer\MailerInterface;
  9. use Symfony\Component\Messenger\Handler\MessageHandlerInterface;
  10. use Symfony\Component\Messenger\MessageBusInterface;
  11. use Symfony\Component\Workflow\WorkflowInterface;
  12. @@ -18,15 +20,19 @@ class CommentMessageHandler implements MessageHandlerInterface
  13. private $commentRepository;
  14. private $bus;
  15. private $workflow;
  16. + private $mailer;
  17. + private $adminEmail;
  18. private $logger;
  19. - public function __construct(EntityManagerInterface $entityManager, SpamChecker $spamChecker, CommentRepository $commentRepository, MessageBusInterface $bus, WorkflowInterface $commentStateMachine, LoggerInterface $logger = null)
  20. + public function __construct(EntityManagerInterface $entityManager, SpamChecker $spamChecker, CommentRepository $commentRepository, MessageBusInterface $bus, WorkflowInterface $commentStateMachine, MailerInterface $mailer, string $adminEmail, LoggerInterface $logger = null)
  21. {
  22. $this->entityManager = $entityManager;
  23. $this->spamChecker = $spamChecker;
  24. $this->commentRepository = $commentRepository;
  25. $this->bus = $bus;
  26. $this->workflow = $commentStateMachine;
  27. + $this->mailer = $mailer;
  28. + $this->adminEmail = $adminEmail;
  29. $this->logger = $logger;
  30. }
  31. @@ -51,8 +57,13 @@ class CommentMessageHandler implements MessageHandlerInterface
  32. $this->bus->dispatch($message);
  33. } elseif ($this->workflow->can($comment, 'publish') || $this->workflow->can($comment, 'publish_ham')) {
  34. - $this->workflow->apply($comment, $this->workflow->can($comment, 'publish') ? 'publish' : 'publish_ham');
  35. - $this->entityManager->flush();
  36. + $this->mailer->send((new NotificationEmail())
  37. + ->subject('New comment posted')
  38. + ->htmlTemplate('emails/comment_notification.html.twig')
  39. + ->from($this->adminEmail)
  40. + ->to($this->adminEmail)
  41. + ->context(['comment' => $comment])
  42. + );
  43. } elseif ($this->logger) {
  44. $this->logger->debug('Dropping comment message', ['comment' => $comment->getId(), 'state' => $comment->getState()]);
  45. }

The MailerInterface is the main entry point and allows to emails.

To send an email, we need a sender (the From/Sender header). Instead of setting it explicitly on the Email instance, define it globally:

patch_file

  1. --- a/config/packages/mailer.yaml
  2. +++ b/config/packages/mailer.yaml
  3. @@ -1,3 +1,5 @@
  4. framework:
  5. mailer:
  6. dsn: '%env(MAILER_DSN)%'
  7. + envelope:
  8. + sender: "%env(string:default:default_admin_email:ADMIN_EMAIL)%"

Extending the Notification Email Template

The notification email template inherits from the default notification email template that comes with Symfony:

templates/emails/comment_notification.html.twig

  1. {% extends '@email/default/notification/body.html.twig' %}
  2. {% block content %}
  3. Author: {{ comment.author }}<br />
  4. Email: {{ comment.email }}<br />
  5. State: {{ comment.state }}<br />
  6. <p>
  7. {{ comment.text }}
  8. </p>
  9. {% endblock %}
  10. {% block action %}
  11. <spacer size="16"></spacer>
  12. <button href="{{ url('review_comment', { id: comment.id }) }}">Accept</button>
  13. <button href="{{ url('review_comment', { id: comment.id, reject: true }) }}">Reject</button>
  14. {% endblock %}

The template overrides a few blocks to customize the message of the email and to add some links that allow the admin to accept or reject a comment. Any route argument that is not a valid route parameter is added as a query string item (the reject URL looks like /admin/comment/review/42?reject=true).

The default NotificationEmail template uses Inky instead of HTML to design emails. It helps create responsive emails that are compatible with all popular email clients.

For maximum compatibility with email readers, the notification base layout inlines all stylesheets (via the CSS inliner package) by default.

These two features are part of optional Twig extensions that need to be installed:

  1. $ symfony composer req "twig/cssinliner-extra:^3" "twig/inky-extra:^3"

In emails, generate URLs with url() instead of path() as you need absolute ones (with scheme and host).

The email is sent from the message handler, in a console context. Generating absolute URLs in a Web context is easier as we know the scheme and domain of the current page. This is not the case in a console context.

patch_file

The SYMFONY_DEFAULT_ROUTE_HOST and SYMFONY_DEFAULT_ROUTE_PORT environment variables are automatically set locally when using the symfony CLI and determined based on the configuration on SymfonyCloud.

Wiring a Route to a Controller

The review_comment route does not exist yet, let’s create an admin controller to handle it:

src/Controller/AdminController.php

  1. namespace App\Controller;
  2. use App\Entity\Comment;
  3. use App\Message\CommentMessage;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\Response;
  8. use Symfony\Component\Messenger\MessageBusInterface;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Symfony\Component\Workflow\Registry;
  11. use Twig\Environment;
  12. class AdminController extends AbstractController
  13. {
  14. private $twig;
  15. private $entityManager;
  16. private $bus;
  17. public function __construct(Environment $twig, EntityManagerInterface $entityManager, MessageBusInterface $bus)
  18. {
  19. $this->twig = $twig;
  20. $this->entityManager = $entityManager;
  21. $this->bus = $bus;
  22. }
  23. #[Route('/admin/comment/review/{id}', name: 'review_comment')]
  24. public function reviewComment(Request $request, Comment $comment, Registry $registry): Response
  25. {
  26. $accepted = !$request->query->get('reject');
  27. $machine = $registry->get($comment);
  28. if ($machine->can($comment, 'publish')) {
  29. $transition = $accepted ? 'publish' : 'reject';
  30. } elseif ($machine->can($comment, 'publish_ham')) {
  31. } else {
  32. return new Response('Comment already reviewed or not in the right state.');
  33. }
  34. $machine->apply($comment, $transition);
  35. if ($accepted) {
  36. $this->bus->dispatch(new CommentMessage($comment->getId()));
  37. }
  38. return $this->render('admin/review.html.twig', [
  39. 'transition' => $transition,
  40. 'comment' => $comment,
  41. ]);
  42. }
  43. }

The review comment URL starts with /admin/ to protect it with the firewall defined in a previous step. The admin needs to be authenticated to access this resource.

Instead of creating a Response instance, we have used render(), a shortcut method provided by the AbstractController controller base class.

When the review is done, a short template thanks the admin for their hard work:

templates/admin/review.html.twig

  1. {% extends 'base.html.twig' %}
  2. {% block body %}
  3. <h2>Comment reviewed, thank you!</h2>
  4. <p>Applied transition: <strong>{{ transition }}</strong></p>
  5. <p>New state: <strong>{{ comment.state }}</strong></p>
  6. {% endblock %}

Using a Mail Catcher

Instead of using a “real” SMTP server or a third-party provider to send emails, let’s use a mail catcher. A mail catcher provides a SMTP server that does not deliver the emails, but makes them available through a Web interface instead:

  1. --- a/docker-compose.yaml
  2. +++ b/docker-compose.yaml
  3. @@ -8,3 +8,7 @@ services:
  4. POSTGRES_PASSWORD: main
  5. POSTGRES_DB: main
  6. ports: [5432]
  7. +
  8. + mailer:
  9. + image: schickling/mailcatcher
  10. + ports: [1025, 1080]

Shut down and restart the containers to add the mail catcher:

  1. $ docker-compose stop
  2. $ docker-compose up -d

You must also stop the message consumer as it is not yet aware of the mail catcher:

  1. $ symfony console messenger:stop-workers

And start it again. The MAILER_DSN is now automatically exposed:

  1. $ sleep 10

You can open the webmail from a terminal:

  1. $ symfony open:local:webmail

Or from the web debug toolbar:

Submit a comment, you should receive an email in the webmail interface:

Step 20: Emailing Admins - 图2

Click on the email title on the interface and accept or reject the comment as you see fit:

Check the logs with server:log if that does not work as expected.

Managing Long-Running Scripts

Having long-running scripts comes with behaviors that you should be aware of. Unlike the PHP model used for HTTP where each request starts with a clean state, the message consumer is running continuously in the background. Each handling of a message inherits the current state, including the memory cache. To avoid any issues with Doctrine, its entity managers are automatically cleared after the handling of a message. You should check if your own services need to do the same or not.

Sending Emails Asynchronously

The email sent in the message handler might take some time to be sent. It might even throw an exception. In case of an exception being thrown during the handling of a message, it will be retried. But instead of retrying to consume the comment message, it would be better to actually just retry sending the email.

We already know how to do that: send the email message on the bus.

A MailerInterface instance does the hard work: when a bus is defined, it dispatches the email messages on it instead of sending them. No changes are needed in your code.

But right now, the bus is sending the email synchronously as we have not configured the queue we want to use for emails. Let’s use RabbitMQ again:

patch_file

  1. --- a/config/packages/messenger.yaml
  2. +++ b/config/packages/messenger.yaml
  3. @@ -19,3 +19,4 @@ framework:
  4. routing:
  5. # Route your messages to the transports
  6. App\Message\CommentMessage: async
  7. + Symfony\Component\Mailer\Messenger\SendEmailMessage: async

Even if we are using the same transport (RabbitMQ) for comment messages and email messages, it does not have to be the case. You could decide to use another transport to manage different message priorities for instance. Using different transports also gives you the opportunity to have different worker machines handling different kind of messages. It is flexible and up to you.

There are many ways to test emails.

You can write unit tests if you write a class per email (by extending Email or TemplatedEmail for instance).

The most common tests you will write though are functional tests that check that some actions trigger an email, and probably tests about the content of the emails if they are dynamic.

Symfony comes with assertions that ease such tests, here is a test example that demonstrates some possibilities:

  1. public function testMailerAssertions()
  2. {
  3. $client = static::createClient();
  4. $client->request('GET', '/');
  5. $this->assertEmailCount(1);
  6. $event = $this->getMailerEvent(0);
  7. $this->assertEmailIsQueued($event);
  8. $email = $this->getMailerMessage(0);
  9. $this->assertEmailHeaderSame($email, 'To', '');
  10. $this->assertEmailTextBodyContains($email, 'Bar');
  11. $this->assertEmailAttachmentCount($email, 1);
  12. }

These assertions work when emails are sent synchronously or asynchronously.

Sending Emails on SymfonyCloud

There is no specific configuration for SymfonyCloud. All accounts come with a SendGrid account that is automatically used to send emails.

You still need to update the SymfonyCloud configuration to include the xsl PHP extension needed by Inky:

patch_file

  1. --- a/.symfony.cloud.yaml
  2. +++ b/.symfony.cloud.yaml
  3. @@ -4,6 +4,7 @@ type: php:7.4
  4. runtime:
  5. extensions:
  6. + - xsl
  7. - pdo_pgsql
  8. - apcu
  9. - mbstring

Note

To be on the safe side, emails are only sent on the master branch by default. Enable SMTP explicitly on non-master branches if you know what you are doing:


This work, including the code samples, is licensed under a license.