Tutorial

Setting the Nice Name in emails sent through Swiftmailer

When using Swiftmailer under Drupal 8 / 9 it automatically sets the headers for sender to be Site Name (variable from site information table) and Site Admin Email (another variable which can be set in site information tab).

I ran into an issue where I needed to set a Nice mail, something like:

"My Name" <info@mywebsite.com>

This is however not possible using default HOOK_mail() function when creating custom mail, and you need to use HOOK_mail_alter().

Pridal/a lubo dňa Ut, 11/08/2022 - 23:44
Setting HOOK_mail() function
function MYMODULE_mail($key, &$message, $params) {
 $options = array(
   'langcode' => $message['langcode'],
 );
 switch ($key) {
   case 'my_mail':
	 
	 if (isset($params['cc'])) {
		 $message['headers']['Cc'] = $params['cc'];
	 }
	 if (isset($params['bcc'])) {
		 $message['headers']['Bcc'] = $params['bcc'];
	 }

     $message['subject'] = t('@subject', ['@subject' => $params['subject']], $options);
     $message['body'][] = $params['message'];
	 
     break;
 }
}

I guess you already have hook_mail() function defined, but if not, this is the code:

 

Using HOOK_mail_alter() function

When testing the code above, I was unable to set the headers properly. This is probably due to the fact, that Swiftmailer sets the headers automatically and can not be overriden in HOOK_mail() function.

So using the HOOK_mail_alter() function solves the problem:

use Drupal\Component\Utility\Unicode;

function MYMODULE_mail_alter(&$message) {
	
  if ($message['id'] == 'MYMODULENAME_MYMAILKEY') { // Typically something like "mymodule_my_mail" in this setting
	  
	$senderName = 'My nicename';
	$nicename = Unicode::mimeHeaderDecode('"' . $senderName . '" <' . \Drupal::config('system.site')->get('mail') . ">");
	 
	$message['headers']['From'] = $nicename;
	
  }
}

 

Might interest you

Tutorial
Sometimes you need to make an adjustements to a cart, or just simply compare the order total or any other property of current user's cart.…
Tutorial
In this tutorial we are going to override any Views Field in your View and populate it with a new data. You can do so by creating a module…

Recommended

Tutorial
1 views
While working on a fairly complex website with very complex views setup, including tens…
Tutorial
6 views
In this case we have two options, either we use hook_user_presave() or we can create new…
Tutorial
4 views
When using Swiftmailer under Drupal 8 / 9 it automatically sets the headers for sender to…
Tutorial
3 views
Yes, IOS / Safari is the new internet explorer. Amount of time I spend on debugging…
Tutorial
10 views
There is a very handy function in Drupal 8 / 9, allowing developers refresh view when…