- 15 views
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;
}
}