Modifying your site's email "From" header

Modifying your site's email "From" header

Posted by stella on Sat, 2009-10-10 13:08 in

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".

Post new comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options