Drupal Symfony Mailer: A Beginner’s Guide

Mayur Upadhyay
Mayur Upadhyay
Drupal Symfony Mailer

Email is one of the most essential parts of any website, whether you’re sending password resets, order updates, or contact form replies. But in Drupal, handling email isn’t always plug-and-play. That’s where Drupal Symfony Mailer steps in, offering a modern, flexible, and reliable way to send emails directly from your Drupal site.

Unlike older email systems, Symfony Mailer gives you more control over formatting, delivery, and integration with services like SendGrid or Mailgun. It’s built on Symfony components, which Drupal core already uses in the backend. So it’s a natural fit for advanced email handling.

Whether you’re building a custom module or managing a business site, it’s smart to hire Drupal development professionals to ensure email is set up the right way. In this blog, we’ll show you how to configure, test, and send emails in Drupal using Symfony Mailer.

What is Symfony Mailer and Why Does It Matter?

When Drupal sends an email, be it for account registration, password resets, or contact form submissions, it needs a backend service to handle the actual delivery. That’s where Symfony Mailer comes in.

Symfony Mailer is a PHP component from the Symfony framework that provides a modern, flexible way to send emails using different methods like SMTP, Sendmail, or third-party APIs (e.g., Mailgun, SendGrid). It replaced the older SwiftMailer library, which is now deprecated.

Here’s an example of a basic Symfony Mailer usage in Drupal via Dependency Injection:

use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
public function sendEmail(MailerInterface $mailer) {
  $email = (new Email())
    ->from('you@example.com')
    ->to('user@example.com')
    ->subject('Welcome Email')
    ->html('<p>Welcome to our platform!</p>');
  $mailer->send($email);
}

This modern mailing system gives Drupal developers more control and a cleaner approach to handling emails. It’s a meaningful step forward for projects that rely on consistent and customizable email functionality.

How Email Works in Drupal?

Drupal comes with a built-in mail system that handles email delivery across the platform. Whether it’s a password reset, a user notification, or an email from a custom module, Drupal uses the same system to construct and send messages. This system is built on a plugin-based architecture, which makes it both flexible and extensible.

Core Components

At the core of Drupal’s mail system is the MailManagerInterface. This service manages different mail plugins and handles the actual sending of emails. To get started, you use the Mail Manager service like this:

$mailManager = \Drupal::service('plugin.manager.mail');

To send an email, you can call the mail() method:

$mailManager->mail($module, $key, $to, $langcode, $params);

Here’s what each parameter means:

  • $module: The module name sending the email.
  • $key: A unique identifier for the type of email.
  • $to: Recipient’s email address.
  • $langcode: Language code.
  • $params: Array of message data (subject, body, etc.).

This method handles the preparation and routing of the email to the appropriate plugin for delivery.

Defining the Email Content: hook_mail()

Before sending, Drupal needs to know what the email should say. That’s where hook_mail() comes in. Each module that sends email should implement this hook to define the content of the email, specifically the subject and body. Here’s a simple example:

function example_module_mail($key, &$message, $params) {
  switch ($key) {
    case 'custom_notification':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}

This hook gives you full control over how the email is structured before it’s passed to the mail plugin. You can dynamically set the subject and body based on the parameters provided when calling mail().

Struggling with Drupal Email Setup? Let Us Configure it For You!

How to Set Up Drupal Symfony Mailer?

To send emails through Drupal using Symfony Mailer, you need to configure how messages are delivered, whether through SMTP, an API service, or a local testing tool. The setup slightly varies depending on your Drupal version and use case.

SMTP Configuration (Drupal 9.4+)

If you’re using Drupal 9.4 or later, Symfony Mailer is already part of core. You just need to configure SMTP settings in your settings.php file:

$config['swiftmailer.transport'] = 'smtp';
$config['swiftmailer.smtp_host'] = 'smtp.example.com';
$config['swiftmailer.smtp_port'] = 587;
$config['swiftmailer.smtp_encryption'] = 'tls';
$config['swiftmailer.smtp_username'] = 'your_username';
$config['swiftmailer.smtp_password'] = 'your_password';

This setup allows you to send emails through providers like Gmail, Outlook, or any custom SMTP server.

Using the symfony_mailer Module (For Drupal < 9.4)

If you’re on Drupal 9.3 or below, the core still uses SwiftMailer. To adopt Symfony Mailer without upgrading core, use the contributed Symfony mailer module.

Here’s how to install:

composer require drupal/symfony_mailer
drush en symfony_mailer

Configuration in settings.php:

$settings['symfony_mailer_dsn'] = 'smtp://user:pass@smtp.example.com:587';

Once enabled and configured, this module replaces SwiftMailer and allows Symfony-style mail sending.

Using services.yml for Custom Transports

For advanced needs, such as API-based services like SendGrid or Mailgun, define custom transport services in your module’s services.yml:

services:
  custom.mail.transport:
    class: Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport
    arguments: ['smtp.sendgrid.net', 587, 'tls']

This method is useful for complete control over how and where your emails are sent.

Local Testing with Mailhog or Mailcatcher

To safely test email sending during development:

  • Mailhog: It intercepts mail and displays it via a web UI.
  • Mailcatcher: It’s a lightweight tool that captures outgoing emails locally.

Using these tools ensures no real emails are sent during development. Whether you’re setting up SMTP, using a contributed module, or testing locally, Symfony Mailer offers flexible ways to integrate email sending into your Drupal site. Once configured, you’re ready to start sending emails programmatically or through custom workflows.

How to Send Emails Programmatically in Drupal?

Once you’ve set up Symfony Mailer in your Drupal site, you can start sending emails through your own code. Whether it’s for user notifications, form submissions, or custom alerts, Drupal provides two main ways to send emails programmatically. For email marketing campaigns or newsletters, you can also consider using tools like the Drupal Mailchimp module.

Method 1: Using Drupal’s MailManager Service

This is the traditional and most common way to send emails in Drupal—especially within custom modules.

Step 1: Call the Mail Service

Use the MailManager service to prepare and send your email:

$mailManager = \Drupal::service('plugin.manager.mail');
$params['subject'] = 'Test Email';
$params['message'] = 'This is a test email sent using MailManager.';
$result = $mailManager->mail('custom_module', 'example', 'user@example.com', 'en', $params);

Here, you’re passing in the module name, email key, recipient email, language code, and your email content.

Step 2: Define the Email with hook_mail()

In your module’s .module file, you need to define what the email should look like using hook_mail():

function custom_module_mail($key, &amp;$message, $params) {
  switch ($key) {
    case 'example':
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['message'];
      break;
  }
}

This step formats the subject and body before Drupal sends the email. You can include text, dynamic values, and even HTML if needed.

Method 2: Using Symfony Mailer via Dependency Injection

For modern projects, especially those using services and controllers, you can work directly with Symfony’s Mailer component for more control and flexibility.

Start by injecting the MailerInterface into your service or controller and use the Email class to build your message.

use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
public function sendEmail(MailerInterface $mailer) {
  $email = (new Email())
    ->from('you@example.com')
    ->to('user@example.com')
    ->subject('Welcome!')
    ->text('Thanks for signing up.')
    ->html('<p>Thanks for <strong>signing up</strong>.</p>');
  $mailer->send($email);
}

This method lets you craft fully custom emails, including HTML layouts and advanced headers using Symfony’s full feature set.

How to Create Templated HTML Emails Using Twig?

Plain-text emails work, but they often feel outdated and don’t reflect your brand well. For a better user experience and professional appearance, Drupal lets you create HTML email templates using Twig, the same templating system used for rendering Drupal pages.

Step 1: Create a Twig Email Template

Start by creating a Twig template file in your custom module or theme. For example:

email--welcome.html.twig
<table style="font-family: Arial, sans-serif; width: 100%;">
  <tr>
    <td>
      <h2>Welcome, {{ username }}!</h2>
      <p>Thanks for joining our platform. We’re excited to have you onboard.</p>
    </td>
  </tr>
</table>

This file sets up the structure and style of your email. You can use Twig placeholders like {{ username }} to insert dynamic content for each recipient.

Step 2: Render the Template in Code

In your module or service, use Drupal’s renderer service to render the template with your dynamic data:

$render = [
  '#theme' => 'email__welcome',
  '#username' => 'John',
];
$body = \Drupal::service('renderer')->renderPlain($render);

Here, the #theme key maps to the Twig template name (email–welcome.html.twig becomes email__welcome in code). You can pass any variable, like username, into the template.

Step 3: Set the Email Body

Now, add the rendered HTML content to your email body:

$message['body'][] = $body;

If you want to include a plain-text fallback (for clients that don’t support HTML), you can strip out the tags:

$message['body'][] = strip_tags($body); // optional fallback

Using Twig for emails allows you to create reusable, brand-consistent templates that look great in any inbox. It’s a big step up from sending plain-text messages.

How to Integrate with Third-party Email Services?

If you’re running a high-traffic website or want better email tracking, delivery rates, or performance, integrating with a third-party email service is a smart move. Thanks to Symfony Mailer, services like Mailgun, SendGrid, and Postmark are easy to connect using DSNs (Data Source Names).

Mailgun, SendGrid, Postmark (via DSN)

Symfony Mailer supports native integrations for many providers. Here’s how to connect them:

Step 1: Install the Mailer Transport

Use Composer to install the transport for your chosen service. For example:

composer require symfony/mailgun-mailer

You can do the same for others:

  • symfony/sendgrid-mailer
  • symfony/postmark-mailer

Step 2: Configure the DSN in settings.php

Add the DSN string with your credentials:

$settings['symfony_mailer_dsn'] = 'mailgun+https://API_KEY@yourdomain.com';

Just replace API_KEY and yourdomain.com with your actual provider info.

Using SMTP-Based Modules (Optional)

Some email services also support SMTP. If you prefer configuring your email settings through Drupal’s UI rather than code, you can use contributed modules like:

  • SMTP Mailer
  • PHPMailer SMTP
  • Mailjet SMTP

These modules let you enter SMTP settings from the admin interface, making setup easier for site builders.

Need a Custom Drupal Site? Our Experts Can Turn Your Dreams Into Reality!

FAQs on Drupal Symfony Mailer

How to use Symfony Mailer in Drupal?

To use Symfony Mailer in Drupal, just install and enable the symfony_mailer module. It will automatically take over the default mail system; no need for the Mail System module. Once enabled, all your Drupal emails will be sent using Symfony Mailer.

What is the alternative to Swiftmailer in Drupal?

The alternative is Drupal Symfony Mailer Lite. It replaces the now-deprecated Swiftmailer module and lets you send HTML emails and attachments using the newer Symfony Mailer library.

How to replace Swiftmailer with Symfony Mailer?

First, uninstall both the Swift Mailer and Mail System modules. Then install the Symfony Mailer and its back-compatibility module using Composer. After that, define your email transport (SMTP or API) and set it as the default.

Conclusion

Symfony Mailer makes it easier to send emails in Drupal, whether you need plain messages or fully designed HTML templates. It’s modern, flexible, and works well with services like Mailgun or SendGrid.

We’ve covered how to set up Symfony Mailer, create Twig templates, and send emails using both Drupal’s MailManager and Symfony’s service approach. With these tools, your site can send professional emails that look great and arrive reliably.

If you’d rather not deal with the setup yourself, our team offers expert Drupal development services. We’ll help you get everything working smoothly, so you can focus on what matters most.

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Related Blog Posts

drupal cdn

Using a CDN with your Drupal site can dramatically improve speed, performance, and security. It reduces load times, handles traffic spikes, and lowers server stress...

drupal coding standards

Drupal coding standards help developers write clean, consistent, and secure code across PHP, JavaScript, CSS, and Twig. Following these guidelines makes teamwork smoother, reduces errors,...

drupal commerce payment gateways

Choosing the right payment gateway for your Drupal Commerce store can shape the entire checkout experience. From PayPal to Stripe, this blog breaks down the...