Managing Mail Handling for Development or Testing

Last updated on
26 May 2022

While debugging, testing or coding new features, you may want to see the content of email sent by your Drupal installation, but you almost certainly won't want any test emails going to real users who may be in your database. Your development platform can be set up so email is safely redirected somewhere you can find it.

Most of the notes that follow should be applicable to all platforms (Linux, Mac, Microsoft).

Modules that manipulate email

Maillog / Mail Developer
Maillog provides an easy possibility to log all Mails for debugging purposes. It's possible to prevent the mails from being sent, so there is no need for an extra mail server to test the mail functionality of other modules or the drupal core. Additionally, you can immediately display the mail through the devel dpm() facility.
Mail Safety

A simple and safe way to test and debug outgoing emails without having to worry that all your users will get unwanted emails.

  • A dashboard that catches and logs all outgoing e-mails
  • Protect your development, test and staging environments by catching e-mails
  • Able to view all emails that are caught by Mail Safety
  • Debug all mails and see their options and structure
  • Able to send the caught e-mails to their original recipient
  • Able to redirect a caught e-mail to a specific recipient
  • Able to redirect all e-mails to a specific recipient
Reroute email
It intercepts all outgoing emails and reroutes them to an address you specify. This is very useful in development when you have a copy of a live site with thousands of users, and modules that send emails (e.g. subscriptions), so the email does not go to real users from the copy site. You can also add debug info in the email if you wish via a theme function.
SMTP Authentication Support
This module allows Drupal to bypass the PHP mail() function and send an email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.
PHPMailer SMTP
Send emails via SMTP using the latest PHPMailer library. It aims to be RFC compliant and robust, leaving the heavy lifting to the PHPMailer library. It supports debugging and advanced SMTP configuration such as setting the envelope sender via the UI.
Shared Email Module
This overrides the 'user' module's validation that prevents the same email address being used by more than one user. Works for both registration and account updates. Displays a warning to the user that they are using a shared email.
Development Environment
This module aims to provide various settings that are specific to development environments only. Currently, the module provides the following functionality with respect to mail: No emails will be sent from the system, and instead will be logged to the Drupal log (watchdog). Whenever a mail is attempted to be sent from the system, users will receive a message informing them that the mail was not sent, and users with 'view site reports' permission will also receive a link to the watchdog. The regular mail stating that a mail was sent is suppressed (only in English for now). This module also enables some development modules if they're available.

Use hook_mail_alter()

In your custom module, you can implement hook_mail_alter() and change sender, recipient and even stop it from sending all-together.

This alters all mail sent with drupal_mail(), so it covers everything Drupal core sends and modules true to the Drupal API.

Example usage to stop all mail during migration, say if your migration module is called example_migrate.module:

/**
 * Implements hook_mail_alter().
 *
 * Don't send any mail during migration.
 */
function example_migrate_mail_alter(&$message) {
  if (class_exists('Migration') and Migration::currentMigration()) {
    $message['send'] = FALSE;
  }
}

Aliasing Your Existing Mail Account

When multiple email accounts are needed, many mail providers, such as Gmail, allow for email aliasing. This allows for multiple Drupal accounts to be sent to a single mail account.

For example, if your email account is example@gmail.com, you can also receive email at example+user1@gmail.com, example+user2@gmail.com, etc.

This can also be used to redirect multiple real user email address to another account. This is useful if you have a dev or test environment that is a dump of your live environment with real user data. This SQL statement will update all your email addresses so that no actual emails go out to your live users.

UPDATE users

SET mail = CONCAT('youremail+',CONCAT(REPLACE(mail, '@', '.AT.'),'@gmail.com'))

Change "youremail" to the first part of the email address you plan to use. For example, if you want to send an email to john@gmail.com, change youremail to john.

This is known to work for Google Apps Mail (which is Gmail) as well. In that case, you should change "gmail.com" to your own domain. If you receive an email at admin@example.com, then your domain is example.com.

Drush

If you use Drush, you can use the --sanitize option to sql-sync when you clone your development database from Staging or Production. This will obfuscate users' e-mail addresses, but there's also an option to set them all to something specific: --sanitize-email.

If you already have a database you'd like to update, then you can run the following from your site directory.

drush sqlq "UPDATE users SET mail = CONCAT('youremail+', CONCAT(REPLACE(mail, '@', '.AT.'), '@gmail.com'))"

Make sure that you do this on the right database! You can check the database Drush will use by running drush sql-conf

PHP CLI Script

This is covered nicely by chx at http://www.drupal4hu.com/node/55 . In short: you set PHP to send mails to a file.

In some distributions of Linux, you have to make sure to install the package php-cli.

Mail to Database Log (Drupal 6)

The Drupal 6 version of the Devel module ships with a smtp_library implementation which logs emails to the Watchdog.

Once the Devel module is installed, go to Administer -> Site configuration -> Devel settings. On that page, there is a section titled SMTP library. Select 'Log only'. After sending an email from your site, go to Administer -> Reports -> Recent log entries. Among the log, you should now see any outgoing messages. By clicking on the text under the 'Message' column you can see more details about that specific message.

Mail to Database Log (Drupal 7, Drupal 8)

The Helper module has a mail handler that writes all emails to the database log. After sending an email from your site, go to Administer -> Reports -> Recent log entries, and you can view the email's details. To switch your site's mail handler to Helper's, add the following inside settings.php:

// Drupal 8:
$config['system.mail']['interface']['default'] = 'helper_logger';

// Drupal 7:
$conf['mail_system'] = array('default-system' => 'HelperDebugMailLog');

Mail to Variable table (Drupal 7)

If you wish to prevent mails from being sent without installing a single module, this solution is the best. This solution comes from the simpletest framework, it's the easiest to set up but makes it harder to read sent mails. To disable mail sending, add the following to your site's settings.php file:

$conf['mail_system'] = array('default-system' => 'TestingMailSystem');

Mail to Temp Files (Drupal 7)

The watchdog logging functionality was removed in the Drupal 7 version of the Devel module, in favor of logging to temporary files instead. To enable temp file logging, add the following to your site's settings.php file:

$conf['mail_system'] = array('default-system' => 'DevelMailLog');

Each individual outgoing message will then be written to its own file in the temporary directory designated for the site (typically /tmp). To log to a different directory, add the following to your site's settings.php file:

$conf['devel_debug_mail_directory'] = '/path/to/directory';

More information can be found in the documentation for DevelMailLog.

Mail to state system (Drupal 8)

Drupal provides a mail backend that captures sent messages in the state system. This is the easiest way to prevent mails from being sent on your local environment, although not the easiest to check after. To disable mail sending, add the following to your site's settings.php file or your settings.local.php file:

$config['system.mail']['interface']['default'] = 'test_mail_collector';

If you use Drush, you can then check the emails sent by running:

drush sget system.test_mail_collector --format=var_dump

Mail to Temp Files (Drupal 8)

The Devel module comes with a mail backend, that saves emails as temporary files. To use it, add the following to your site's settings.php file or your settings.local.php file:

$config['system.mail']['interface']['default'] = 'devel_mail_log';

Each individual outgoing message will then be written to its own file in a devel-mails subdirectory of the temporary directory designated for the site (typically /tmp). To log to a different directory, add the following line:

$config['devel.settings']['debug_mail_directory'] = 'temporary://my-directory';

You can also specify an absolute path to the directory if you want.

More information can be found in the documentation for DevelMailLog.

Fakemail

Fakemail is a Perl script that just works out of the box as long as you have Perl installed. You just run the script, it listens on port 25 and dumps all mail received into a directory. You have no risk of the spurious email being delivered to users by means of your sandbox.

MailCatcher

MailCatcher is a simple SMTP server that can catch all emails sent by various systems including PHP. Such emails can then be viewed from MailCatcher's web interface which is available at http://localhost:1080/ by default. Briefly, setup involves two steps:

  1. Install the MailCatcher Ruby gem: sudo gem install mailcatcher
  2. Tell PHP to use MailCatcher for sending emails. On Unix-like systems, this can be done by setting the sendmail_path PHP configuration directive to /usr/bin/env catchmail -f from@domain

More detailed setup instruction is also available. Servers for Hackers has a good tutorial for Ubuntu/Debian users. The article "debugging emails in Symfony 2/3 and Drupal 7/8" shows how to debug emails with MailCatcher in Drupal.

MailHog

MailHog is inspired by mailcatcher and pretty easy to use. Full instructions are provided.

  1. Install it any way you like (including homebrew on MacOS with brew install mailhog)
  2. Configure PHP to use it for sending mail by adding to your php.ini
    sendmail_path = "/path/to/mailhog sendmail test@example.org"
    (if you used brew to install. the path will be /usr/local/bin/mailhog.)
  3. Restart apache or php-fpm
  4. Mail from any PHP use, including Drupal sites, will be sent via mailhog, and can be viewed by using the very nice web interface at http://localhost:8025

It's quite easy to add to Lando, by adding a few lines in the .lando.yml config file.

Dummy sendmail

This is a one-line script - only suitable for dev/test boxes - that redirects mail sent via the sendmail command (PHP's default mechanism in most cases) to a file. This won't catch mail sent to port 25/SMTP but is sufficient in most setups and doesn't rely on any special Drupal setup. You will want to first remove any running mail transfer agents, as well as whatever package owns the /usr/bin/sendmail command, then create a file with a text file containing:

#!/usr/bin/env sh
cat >> /tmp/mail

Make this executable using the command chmod a+x /usr/bin/sendmail - all sent mail will then be redirected to the /tmp/mail file.

Alternatively, you can save this script to another file (instead of replacing /usr/bin/sendmail) and set sendmail_path=/path/to/file in your php.ini.

Mail Transfer Agents

If you wish to have a more complete solution, you can use a mail transfer agent like Postfix, Exim or Sendmail.

Postfix

Postfix is a well-known and widely used free-and-open-source mail transfer agent.

To use Postfix, it must be installed on your server, or a server you have command-line access to. Installation and configuration of Postfix is beyond the scope of this page, however there is documentation available. Postfix runs on Linux, OSX, Unix or under Windows using Cygwin.

Here is the minimum configuration you will need: in /etc/postfix/main.cf configure

myhostname = <the hostname of your box> #if it is simply 'localhost', you can leave this line commented out.
inet_interfaces = localhost # so that it won't be an open relay
mydestination = $myhostname, localhost

You can find more complete documentation on how to configure Postfix on the Basic Postfix Configuration page.

To read emails using a command line reader such as the mail command, pine, elm, or mutt, a user account must be created on your server. In this example, the user would be "mailtest."

Then, to use this account, send mails to mailtest@
and read it using the command line reader.

Postfix can also relay messages to any mail account, such as Gmail, Yahoo, Hotmail.

Exim

Exim is another well-known free and open-source mail transfer agent. It runs on Linux or under Windows using Cygwin. Create a user account and read the mail using the mail command, pine, elm, mutt or other mail readers as described above. Exim can also relay messages to any mail account such as Gmail, Yahoo, Hotmail, etc.

Sendmail

Sendmail is another powerful mail transfer agent, however it is often described as difficult to configure.

sSMTP

sSMTP is a simple MTA to deliver mail from a computer to a mail hub (SMTP server) like e.g. Gmail. sSMTP is simple and lightweight, there are no daemons or anything hogging up CPU.

To install ssmtp: sudo apt-get install ssmtp
Configure ssmtp: sudo nano /etc/ssmtp/ssmtp.conf
Possible configuration using Gmail:

    root=john.smith@gmail.com
    mailhub=smtp.gmail.com:587
    hostname=john.smith@gmail.com
    UseSTARTTLS=YES
    AuthUser=john.smith
    AuthPass=john1978
    FromLineOverride=YES

Configure php: In php. ini change: sendmail_path = /usr/sbin/ssmtp -t

More: http://codekarate.com/blog/sending-emails-your-ubuntu-drupal-development...

MailServe

On OSX, MailServe provides another option, although it is not free or open-source.

Free SMTP Server

This Windows application provides an SMTP server.

Third-Party Solutions

mailtrap.io

mailtrap.io - This is a free (for the present time at least, I don't know if they plan to have people start paying later) freemium service that allows you to configure postfix/phpmailer/whatever you use to send mail to mailtrap.io instead. Mailtrap will put it in its inbox on their servers. Paid versions allow forwarding to personal e-mail addresses as well as giving "inbox" access to other mailtrap.io users so that multiple people can view the same mailbox.

Help improve this page

Page status: No known problems

You can: