8 – hook_mail_alter() doesn’t remove the Return-Path, Sender, and Reply-To headers

Removing the values from $message('headers') isn’t sufficient, as the plugin used to send emails could also use $message('Return-Path'), $message('Sender'), or $message('Reply-To') value to build the email headers. The class that is used as default plugin to send emails, PhpMail uses the following code, but other plugins could use different code.

$site_mail = $this->configFactory->get('system.site')->get('mail');
$additional_headers = isset($message('Return-Path')) && ($site_mail === $message('Return-Path') || static::_isShellSafe($message('Return-Path'))) ? '-f' . $message('Return-Path') : '';
$mail_result = @mail($message('to'), $mail_subject, $mail_body, $mail_headers, $additional_headers);

Since the email plugin is used to send the email after the hook_mail_alter() implementations are invoked, and since the email plugin can add one of those headers to its discretion, there isn’t any warranty the email is sent without those headers. Assuming the email plugin adds only those headers when $message or $message('headers') contains a value for them, the following code should work.

function mymodule_mail_alter(&$message) {