Category Technology
Publication date
10 October 2009

Modifying your site's email "From" header

By default, all email sent from your site uses the site email address configured at admin/settings/site-information as the "from" address. On most sites this is set to something generic, like "webmaster@example.com" or "noreply@example.com". However in a lot of mail clients, when the email reaches your inbox, it appears as being just from "webmaster" or "noreply". Wouldn't it be better if it appeared as being from "Your site" or whatever you have set your site name to be?

You can achieve this easily with just a few lines of code in a custom module:

<?php
/**
 * Implements hook_mail_alter().
 */
function your_module_mail_alter(&$message) {
  $site_name = variable_get('site_name', '');
  $site_mail = variable_get('site_mail', '');
  if (!empty($site_name) && $site_mail == $message['from']) {
    $message['from'] = '"'. mime_header_encode($site_name) .'" <'. $site_mail .'>';
    $message['headers']['From'] = '"'. mime_header_encode($site_name) .'" <'. $site_mail .'>';
  }
}
?>

The above function retrieves the site name and email address that you configured on admin/settings/site-information.  Then for each email sent from the site, if the "from" email address matches the site address, it modifies the From header to include the site name as well.  This produces the nice user-friendly effect where emails in your inbox appear to be from "Your site" rather than just "webmaster".

Profile picture for user Stella Power

Stella Power Managing Director

As well as being the founder and managing director of Annertech, Stella is one of the best known Drupal contributors in the world.