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

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:

1
2
$headers = 'From: Company <[email protected]>' . "\r\n";
wp_mail($email, $subject, $message, $headers);
$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:

1
2
3
4
5
6
7
8
9
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';
}
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:

1
2
remove_filter('wp_mail_from','custom_wp_mail_from');
remove_filter('wp_mail_from_name','custom_wp_mail_from_name');
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.

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

  1. room34

    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!

    Reply
  2. Sepehr Sadighpour

    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.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *