Drupalwoo ☉

Creating A Drupal Module With Symfony Mailer

Transactional email is part of many Drupal workflows: account verification, password resets, invoices, booking confirmations, delivery updates, and security alerts. These messages are triggered by a site event and contain information that a user expects to receive promptly.

Symfony Mailer provides a modern transport layer for sending these messages through SMTP, a local relay, or a third-party provider. In Drupal, the cleanest implementation usually combines Symfony Mailer with Drupal’s mail manager, configuration system, translation support, and queue API.

This approach keeps the custom module small while allowing administrators to change delivery settings without editing PHP. It also makes the feature easier to test on a local environment before it is released to a production site serving customers in Sydney, Melbourne, Brisbane, or elsewhere in Australia.

A reliable email feature needs more than a subject line and a recipient address. It should handle configuration, failures, privacy, logging, duplicate events, and the distinction between a genuine service message and promotional content.

Choose The Drupal Email Architecture

Drupal already provides a mail abstraction through MailManagerInterface. A custom module can call this service, define a hook_mail() implementation, and let the configured Symfony Mailer backend deliver the message. This is preferable to opening a separate SMTP connection in every event subscriber.

The module should have three separate responsibilities. An event subscriber or controller decides when an email is required, a mail-building function prepares the subject and body, and the configured mail backend sends it. Keeping these concerns separate makes later changes—such as adding HTML templates or a queue—far less disruptive.

For example, an order confirmation should be triggered after the order has reached the correct state, rather than simply after an add-to-cart action. A login alert should be generated only when the relevant event has been identified and duplicate notifications have been considered. A useful reference for this pattern is the login event tutorial, which demonstrates how a Drupal module can respond to user authentication activity.

Create The Custom Module

A minimal module might be called transactional_notice. Its directory can contain the following files:

modules/custom/transactional_notice/
├── transactional_notice.info.yml
├── transactional_notice.services.yml
├── transactional_notice.module
└── src/
    └── Service/
        └── TransactionalNoticeSender.php

The .info.yml file declares the Drupal version and a dependency on the Symfony Mailer integration used by the site:

name: Transactional Notice
type: module
description: Sends event-based email through Drupal's configured mail system.
core_version_requirement: ^10 || ^11
package: Custom
dependencies:
  - drupal:user
  - symfony_mailer:symfony_mailer

The exact dependency name can differ between Symfony Mailer projects and Drupal releases. Check the module’s machine name before enabling the custom module. After copying the files into place, enable it with Drush:

drush en symfony_mailer transactional_notice -y
drush cr

A service definition allows Drupal to inject the mail manager rather than relying on global service calls:

services:
  transactional_notice.sender:
    class: Drupal\transactional_notice\Service\TransactionalNoticeSender
    arguments: ['@plugin.manager.mail', '@language_manager']

This structure follows Drupal’s dependency injection conventions and makes the sender easier to replace in a kernel test.

Configure Symfony Mailer Transport

The Symfony Mailer module normally provides configuration for the transport used by Drupal’s mail system. Depending on the chosen version, an administrator may configure SMTP, sendmail, a development transport, or a provider-specific DSN through the Drupal interface or settings files.

Production credentials should not be committed to Git. Use environment variables in settings.php, a secrets manager, or deployment variables. A typical DSN conceptually looks like this:

smtp://username:password@mail.example.com:587

The real value should be protected and URL-encoded where necessary. Port 587 commonly uses authenticated submission with STARTTLS, while port 465 is generally associated with implicit TLS. The provider’s documentation should determine the final settings.

Set a stable sender address such as notifications@example.com, and ensure the domain has SPF, DKIM, and DMARC configured. These DNS records do not replace Symfony Mailer, but they greatly improve deliverability. Australian organisations often use cloud-hosted mail services with data centres outside the country, so document the provider and review whether that arrangement matches the organisation’s privacy policy and contractual commitments.

Development and production transports should be different. On a local machine, route all mail to a capture tool or a controlled mailbox. A temporary test inbox can be useful for inspecting message output without exposing real customer addresses, provided the service is suitable for the data being sent.

Build A Reusable Mail Sender

The sender service can wrap Drupal’s mail manager and pass structured parameters to hook_mail(). This preserves Drupal’s language handling and allows the Symfony Mailer backend to remain configurable:

<?php

namespace Drupal\transactional_notice\Service;

use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;

final class TransactionalNoticeSender {

  public function __construct(
    private MailManagerInterface $mailManager,
    private LanguageManagerInterface $languageManager,
  ) {}

  public function sendReceipt(string $email, string $orderNumber, string $total): bool {
    $language = $this->languageManager->getCurrentLanguage();
    $params = [
      'order_number' => $orderNumber,
      'total' => $total,
    ];

    $result = $this->mailManager->mail(
      'transactional_notice',
      'receipt',
      $email,
      $language->getId(),
      $params,
      NULL,
      TRUE
    );

    return !empty($result['result']);
  }

}

The final boolean argument requests immediate sending. That is acceptable for a low-volume message where the user must receive a response immediately, but it can slow down a web request if the mail server is unavailable. For invoices, exports, or large notification campaigns, use Drupal’s queue API instead.

The corresponding hook_mail() function can keep message construction predictable:

function transactional_notice_mail(
  $key,
  &$message,
  $params
): void {
  if ($key === 'receipt') {
    $message['subject'] = t(
      'Receipt for order @number',
      ['@number' => $params['order_number']]
    );

    $message['body'][] = t(
      "Thank you for your order.\n\nOrder: @number\nTotal: @total",
      [
        '@number' => $params['order_number'],
        '@total' => $params['total'],
      ]
    );
  }
}

Use placeholders rather than concatenating untrusted values into markup. If an HTML email is required, create a Twig template and pass escaped variables to it. Keep a readable plain-text alternative because some recipients, mail clients, and assistive technologies handle text messages more reliably.

Compare Delivery Patterns

Different Drupal sites need different levels of control. A small membership site may need only one event and a standard SMTP connection, while a busy ecommerce platform may require queue workers, provider webhooks, and delivery monitoring.

Approach Strengths Trade-offs Suitable use
Drupal mail manager with Symfony Mailer Drupal-native, translatable, configurable, easy to test Requires understanding Drupal mail hooks Most transactional module features
Direct Symfony Mailer service Fine-grained control over Email objects and headers Bypasses some Drupal mail conventions and configuration Specialised messages or a dedicated integration
Queue worker with Symfony Mailer Keeps web requests fast and retries failures Delivery is asynchronous and needs worker monitoring Receipts, reports, bulk notifications
Third-party provider API Detailed delivery events, suppression handling, analytics External dependency, cost, and data-transfer considerations High-volume or reputation-sensitive sending

For most custom Drupal modules, start with the Drupal mail manager and Symfony Mailer as the transport. Move delivery into a queue when the message is not required before the current HTTP response finishes. A queue item should contain a stable entity ID or notification ID, not a large collection of mutable user data.

Do not treat a successful handoff as proof that the recipient received the email. Symfony Mailer can report that the transport accepted a message, while the provider may later reject, defer, or bounce it. Store a notification status when business reporting requires it, and use provider webhooks where available.

Design For Reliable Delivery

Event-driven email can produce duplicates when a request is retried, a payment callback arrives twice, or an administrator manually repeats an operation. Create an idempotency key such as receipt:order:12345, store it with the notification record, and check it before sending.

A queue worker should catch transport exceptions and allow Drupal to retry according to the queue’s normal behaviour. Permanent errors, such as an invalid recipient address, should be logged clearly without retrying forever. Avoid placing full message bodies, passwords, access tokens, or sensitive customer details in logs.

Practical reliability checks include:

A useful operational distinction is between technical failure and recipient-level failure. A DNS outage or connection timeout may be temporary. A bounced address, blocked domain, or invalid mailbox may require correction in Drupal data. Monitoring should expose both categories to site administrators.

Handle Australian Compliance And Local Context

A transactional email must remain genuinely transactional. Under Australia’s Spam Act 2003, commercial electronic messages generally need consent, sender identification, and a functional unsubscribe mechanism. Some factual messages may qualify for an exemption, but adding a product promotion to an order receipt can change its character. Ask legal counsel to assess the organisation’s particular message types.

The Privacy Act 1988 and the Australian Privacy Principles are also relevant when emails contain names, addresses, invoices, health information, or account details. Do not include more personal information than the recipient needs. Use HTTPS links to protected pages rather than placing sensitive records directly in the email body, and document any overseas mail provider used to process personal information.

Local operating habits matter during implementation. A support team in Perth may inspect an alert while a Sydney-based site operates on a different local schedule, and daylight-saving changes affect the difference between eastern states and Western Australia. Store timestamps in UTC, format them for the recipient’s locale, and avoid hard-coding AEST into message text.

For an Australian retail or service business, delivery expectations also vary by market. A Melbourne customer may expect a booking confirmation within seconds, while a low-priority weekly account summary can safely run through an overnight queue. Keep service messages separate from newsletters so consent records, unsubscribe handling, and reporting remain clear.

Test And Deploy The Module

Test the sender at several layers. A unit test can verify that the correct parameters are passed to the mail manager. A kernel test can enable the module and check Drupal configuration. A functional test can trigger the real event and confirm that the expected recipient, language, subject, and body are produced.

Before production deployment, verify the complete path from event to transport. Check a plain-text client, an HTML-capable client, a mobile device, and a mailbox using a different provider. Test non-ASCII names, long order numbers, invalid addresses, missing optional values, and a failed SMTP connection.

A compact release checklist is:

Enable configuration management for mail settings that belong in Drupal, but keep secrets outside exported YAML. Clear caches after installing services or changing routing and container definitions. On hosting platforms using Supervisor, cron, or a managed queue runner, confirm that workers actually execute after deployment.

Finally, review the module after upgrading Drupal or the Symfony Mailer integration. Service IDs, configuration schemas, transport options, and PHP compatibility can change between releases. A small custom module with explicit dependencies, injected services, controlled templates, and observable delivery behaviour is far easier to maintain than code that sends raw SMTP commands from an event callback.