Setting a Custom Email Header

Heads up! This article contains PHP code and is intended for developers. We offer this code as a courtesy but don’t provide support for code customizations or 3rd party development.

Overview

Would you like to set custom email headers to all the emails sent from your WordPress site? Adding custom email headers is a great way to add additional information to emails, track email routes, and provide protection from spam.

In this tutorial, we’ll show you how to set custom email headers to ensure you can control specific behaviors of your sent emails.

Note: Be sure to install and activate the WP Mail SMTP plugin on your site before adding the code snippet provided in this tutorial.

Setup

We recommend that you copy and paste the required snippet below into a new WPCode snippet. WPCode makes it easy and safe to run code snippets on your site.

For help with adding snippets to your site, please see our tutorial on adding code snippets using the WPCode plugin.

Simply copy and paste the snippet below to into WPCode. To add a custom header, replace 'X-Custom-Header: header_value' on line 6 with the header name followed by a separator and then the header value.

function wpmsmtp_custom_mail_header($args) {
if ( ! is_array( $args['headers'] ) ) {
$args['headers'] = explode( "\n", str_replace( "\r\n", "\n", $args['headers'] ) );
}

$args['headers'][] = 'X-Custom-Header: header_value';

return $args;
}
add_filter ( 'wp_mail', 'wpmsmtp_custom_mail_header');

You can add additional custom headers similarly by repeating the code and changing the header name and value.

That’s it! Now you know how to successfully add custom headers to all the emails sent from your WordPress site.

Next, want to explore more ways to customize your WP Mail SMTP setup? Be sure to look at our other code snippets for more customization options.