Writing Custom Mail Backends in Drupal 8

Writing mail backends is probably something you won't do very often but this change notice caught my eye because I've been maintaining my own mail backend for Drupal 7 that handles mail in Simpletest when you're using Mime MailDrupal 8 has adopted annotations as a way to describe entities. Blocks, fields, widgets, formatters and more all have their own annotations and now so do mail backends. 

Emails sent using Mime Mail come through in a different format and break the Drupal 7 TestingMailSystem. Mime Mail should probably provide its own testing class but previously I wrote my own. Lets take a look at what a port of that class may look like in Drupal 8.

 * @file
 * Contains \Drupal\Core\Mail\Plugin\Mail\TestMimeMailCollector.
namespace Drupal\Core\Mail\Plugin\Mail;
use Drupal\Core\Mail\MailInterface;
 * Defines a mail backend that captures sent messages in the state system.
 * This class is for running tests or for development.
 * @Mail(
 *   id = "test_mime_mail_collector",
 *   label = @Translation("Mime Mail collector"),
 *   description = @Translation("Save the emails in Drupal for testing.")
 * )
class TestMimeMailCollector extends MimeMailSystem implements MailInterface {
   * {@inheritdoc}
  public function mail(array $message) {
    $captured_emails = \Drupal::state()->get('system.test_mail_collector') ?: array();
    $captured_emails[] = array(
      'to' => $message['to'],
      'subject' => $message['params']['context']['subject'],
      'body' => $message['params']['context']['body'],
    \Drupal::state()->set('system.test_mail_collector', $captured_emails);
    return TRUE;

Turns out it is pretty much identical to Drupal 7. The only difference other than some Drupal 8 specifics like namespaces and an interface is that the mail backends are described and referenced using the annotations rather than the class name. Who said Drupal 8 isn't easy!

Author Info

Ben Dougherty

In his free time Ben can be found lurking in the Drupal issue queues, chatting in #drupal-contribute and listening to Oasis. He is known for his superhuman debugging abilities and occasionally enjoys a beer or two.