A new utility \Drupal\Component\Utility\Mail has been added to Drupal 8 to ensure emails are more compliant with RFCs.
It currently provides only a single helper \Drupal\Component\Utility\Mail::formatDisplayName($string) to process a display-name email component, i.e. the "My Site" piece on From: My Site .
Before:
Drupal and contrib/custom modules could only rely on Unicode::mimeHeaderEncode() method to process display-name components:
use Drupal\Component\Utility\Unicode;
/**
* Implements hook_mail().
*/
function custom_module_mail($key, &$message, $params) {
$message['headers']['From'] = Unicode::mimeHeaderEncode($params['custom_from'], TRUE) . ' <' . $params['custom_from_mail'] . '>';
$message['headers']['Sender'] = Unicode::mimeHeaderEncode($params['custom_sender'], TRUE) . ' <' . $params['custom_sender_mail'] . '>';
$message['headers']['Reply-to'] = Unicode::mimeHeaderEncode($params['custom_reply'], TRUE) . ' <' . $params['custom_reply_mail'] . '>';
}
However this was producing malformed headers on certain conditions (see linked issue to know more).
After:
Drupal core and contrib/custom developers can now use \Drupal\Component\Utility\Mail::formatDisplayName($string) to create display-name components compliant with RFC 2822:
use Drupal\Component\Utility\Mail;
/**
* Implements hook_mail().
*/
function custom_module_mail($key, &$message, $params) {
$message['headers']['From'] = Mail::formatDisplayName($params['custom_from']) . ' <' . $params['custom_from_mail'] . '>';
$message['headers']['Sender'] = Mail::formatDisplayName($params['custom_sender']) . ' <' . $params['custom_sender_mail'] . '>';
$message['headers']['Reply-to'] = Mail::formatDisplayName($params['custom_reply']) . ' <' . $params['custom_reply_mail'] . '>';
}
Developers defining or altering addresses in emails header fields (i.e. From, To, Sender, Reply-To, etc.) are strongly encouraged to use this helper for the display-name component.