4

I'm trying to alter the email and change the default "From" address to a different email address.

function mymodule_mail_alter(&$message){
   $message['from'] = 'myemail@gmail.com';
}

When I test send a test email through my site Contact Form. The email "From" address is still using the default site email not the one I altered in my module.

Is there another way to make this work?
Thanks for your help.

2

I ran into this issue myself. I got it to work in the following way:

function mymodule_mail_alter(&$message){

  $message['from'] = "do-no-reply@example.com";
  $message['headers']['From'] = 'Name TO SHOW <do-no-reply@example.com>';
  $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['from'];
}

However, like you, I thought adding $message['from'] = 'myemail@gmail.com'; is the way to go and I think it should -Perhaps other folks can chime in and let us know if this is a bug?

In any case, it seems drupal does more processing and checks to verify the from email address and if it does not pass all the checks it sets it to the sitemail, or the mail library just use the other headers. Note I think this behavior may differ based on which mail library you are using. In my case, and I presume in yours, its PhpMail.php.

The solution above worked but I am not sure if it's the most appropriate or if it would work for others who are using different mail managers..

1
  • $message['headers'] is what gets used by default (using the default PhpMail plugin) for all the mail headers, including the 'From' header. $message['from'] is ignored by default. This is as designed. It is possible that a different mail plugin might not do the same thing, but it's safest to just assume all plugins do the same thing as the default plugin.
    – anonymous
    Nov 5 '20 at 6:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.