Set the “from” header in the email to be in the format “Full Name” <email@address.com>

drupal.stackexchange https://drupal.stackexchange.com/questions/7311

  •  16-10-2019
  •  | 
  •  

Question

How can I change the from header in the email sent from Drupal to be in the format "Fullname" <email@address.com>?

I managed to do it on a Drupal 6 site at one point in the past, but I no longer have access to that site, and I don't remember how to do it.

Was it helpful?

Solution

You can use hook_mail_alter() to change the "from" email address of any email sent out from your site. The email address used needs to conform to the RFC standard, which it does is your question's title. But user names can be tricky and might contain illegal characters. There's a comment on the D6 docs that provides a code sample for properly formatting the email address. Your code would look something like...

function yourmodule_mail_alter(&$message) {
  $message['from'] = $message['headers']['From'] = '"Full Name" <email@address.com>';
}

Also, keep in mind that just setting the "from" address may not have the desired results in all email clients (see the discussion on the Drupal issue queue). You might also need to set "sender", "errors-to" and "reply-to" based on your requirements. Those values are in the "header" of the $message variable from the code sample above.

OTHER TIPS

This is the method from Drupal 6 to add the the site name to the email. Substitute variable_get('site_name, Drupal') with The Site Full Name you want.

/**
* Implementation of hook_mail_alter().
* Here we allow the site name to be used as the senders name for outgoing email.
* see http://drupal.org/node/209672
*/
function mymodule_mail_alter(&$message){
  $default_from = variable_get('site_mail', ini_get('sendmail_from'));

  if($message['from'] == $default_from){
    $message['from'] = '"'. variable_get('site_name', 'Drupal') .'" <'. $default_from .'>';
    $message['headers']['From'] = $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['headers']['Errors-To'] = $message['headers']['Reply-To'] = $message['from'];
  }
}

the function for hook_mail_alter() has not change in Drupal 7, so this should work.

Regarding the settings you have to change, this is still an issue in D7. If in doubt, use the following code in your hook_mail_alter :

$message['from'] = $from;
$message['headers']['From'] = $from;
$message['headers']['Sender'] = $from;
$message['headers']['Return-Path'] = $from;
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top