Passing in a “from” header to wp_mail() does not work

Blank note card on top of an envelope.
"Paper! Snow! A ghooooost!" -Joey

I ran into an issue today where I was setting the “from” header in wp_mail(), but it didn’t show up when I received the email. The code looks like this:

$headers = 'From: Company <[email protected]>' . "\r\n";
wp_mail($email, $subject, $message, $headers);

I learned that the only reason my “from” header wouldn’t show up correctly is if one of the following filters overwrites it:

add_filter('wp_mail_from','custom_wp_mail_from');
function custom_wp_mail_from($email) {
  return '[email protected]';
}

add_filter('wp_mail_from_name','custom_wp_mail_from_name');
function custom_wp_mail_from_name($name) {
  return 'WordPress';
}

Most likely you have plugin enabled that uses the previous filters to overwrite the “from” header that is being passed into wp_mail().

You have two options to fix the issue:

  1. You disable the plugin that’s causing this.
  2. You overwrite the plugin’s filter by creating another filter right before calling wp_mail().

It would be a good practice for you to remove that filter upon sending the email, especially if you are creating a plugin that’s going to be used by an audience other than yourself. The reason for this is now apparent :).

You can do this via the remove_filter() function:

remove_filter('wp_mail_from','custom_wp_mail_from');
remove_filter('wp_mail_from_name','custom_wp_mail_from_name');

Important: WordPress notes the following:

To remove a hook, the function and priority arguments must match when the hook was added. This goes for both filters and actions. No warning will be given on removal failure.

So if you set a priority, be sure to match it. In my example above, I didn’t specify a priority, so the default of 10 was used.

Featured image by Kate Macate.


Comments (5)

Previously posted in WordPress and transferred to Ghost.

room34
March 28, 2013 at 11:54 am

This was just what I needed! I couldn’t find any instances of any of my active plugins interfering, but nevertheless WordPress was ignoring my “From” headers when calling wp_mail(). I added your filters into my functions.php file and it worked perfectly. Thanks!

Ryan Sechrest
March 28, 2013 at 11:04 pm

Nice, glad it helped!

Maxim
August 14, 2013 at 5:13 pm

Thanks you for this! Very good solution!

Sepehr Sadighpour
December 24, 2014 at 11:49 pm

Thanks, this helped out. Another solution, in case you want to keep the filter around for some reason, would be to give a very late priority to your own filter, so it overrides whatever other plugin/core might be doing.

Sean
March 1, 2016 at 12:12 pm

Awesome. Thanks!