multiple-mail-post

Allow multiple recipients to any WordPress mail

One thing that I get asked over and over for a few years now is how to set multiple recipients to WordPress sent mails or Admin email notifications, So in this tutorial we are going to answer that question and provide a simple yet elegant solution.

The Plan

All (well most) WordPress core, plugins or theme generated emails are sent using wp_mail function which luckily for us means that there are action and filter hooks for us to use and modify or alter the email being sent. We are going to write a simple plugin that will add BCC and CC email addresses to any mail sent using wp_mail.

Coding the plugin

The whole plugin is available for download at GitHub.
To start coding our plugin we create a new file named gwp_bcc_cc_mail.php and we load it up with Standard WordPress Plugin Information header.

<?php
/*
Plugin Name: GWP mail BCC and CC
Plugin URI:
Description: A plugin to add bcc and cc email address to any mail sent by WordPress
Version: 1.0
Author: Ohad Raz
Author URI: https://generatewp.com
*/

then we Create a main class for the plugin with the methods we want to implement:

/**
* GWP_bcc_cc_mail
*/
class GWP_bcc_cc_mail{
	
	/**
	 * __construct
	 * class constructor will set the needed filter and action hooks
	 *
	 */
	function __construct(){}

	/**
	 * wp_mail 
	 * In this method we actually add the cc and bcc address to the wp_mail call
	 * @param  array $args an associative array of mail arguments(to,subject,message,headers,attachments)
	 * @return array       
	 */
	function wp_mail($args){}

	/**
	 * user_contactmethods
	 * In this method we will add cc and bcc fields to the user profile edit screen.
	 * @param  array $user_contact_method an associative array keyed by form field ids with human-readable text as values.
	 * @return array
	 */
	function user_contactmethods($user_contact_method){}
}

Next we are going to implement the class methods and we are going to starts with the user_contactmethods. We are going to add cc and bcc fields to the WordPress Profile edit screen and to do that we are going to use the handy User Contact Methods Generator and we get this:

// Register User Contact Methods
function user_contactmethods( $user_contact_method ) {
	$user_contact_method['cc'] = __( 'CC email address (multiple: Comma separated emails)', 'GWP' );
	$user_contact_method['bcc'] = __( 'BCC email address (multiple: Comma separated emails)', 'GWP' );
	return $user_contact_method;
}
// Hook into the 'user_contactmethods' filter
add_filter( 'user_contactmethods', 'user_contactmethods' );

View snippet Clone snippet Download snippet

This will add two new fields to the user contact methods so the user (each user) can add his own cc and bcc email addresses and the user profile screen look something like this:

User profile fields

Next we implement our class constructor which will hook the class methods to the right action and filter hooks:

    /**
     * __construct
     * class constructor will set the needed filter and action hooks
     *
     */
	function __construct(){
		// Hook into the 'user_contactmethods' filter to add cc and bcc fields
		add_filter( 'user_contactmethods', array($this,'user_contactmethods' ));
		//hook into wp_mail to add cc and bcc as needed
		add_filter('wp_mail',array($this,'wp_mail'));
	}

And last we are going to implement the wp_mail method of our class:

	/**
	 * wp_mail 
	 * In this method we actuly add the cc and bcc address to the wp_mail call
	 * @param  array $args an associative array of mail arguments(to,subject,message,headers,attachments)
	 * @return array       
	 */
	function wp_mail($args){
		//get all emails that are already beeing sent to (users)
		$emails = $args['to'];
		//make sure we proccess them one by one
		$emails = explode(',', $emails);
		//loop over the emails and check if we need to add cc and bcc addresses
		foreach ($emails as $em) {
			//try to get the user id by the "to mail"
			$user = get_user_by( 'email', trim($em));
			if ($user){
				//get user ccs if exists
				$cc = get_user_meta( $user->ID, 'cc', true );
				if ( $cc ){
					//explode by comma "," to allow multiple cc addresses
					$ccs = explode(",", $cc);
					foreach ((array)$ccs as $cc_address) {
						$args['headers'][] = 'Cc: '.trim($cc_address);
					}
				}
				//get user bccs if exists
				$bcc = get_user_meta( $user->ID, 'bcc', true );
				if ( $bcc ){
					//explode by comma "," to allow multiple bcc addresses
					$bccs = explode(",", $bcc);
					foreach ((array)$bccs as $bcc_address) {
						$args['headers'][] = 'Bcc: '.trim($bcc_address);
					}
				}
			}
		}
	    return $args;
	}

Breakdown: Starting on lines 8-11 we get the “to” emails that the current email is being sent to and we split them into an array of emails since some emails are already sent to multiple multiple. Then we loop over each email, on lines 15-16 we try to get the user by current “to” email address and if we do find a user we then on lines 18-19 try to get his Cc email addresses which we then on lines 21-24 add them one by one to the mail headers using the $args['headers'] array. On lines 27-34 we do the same but for Bcc email addresses and to make sure our email is sent we return the $args array.

Upgrade to GenerateWP Premium Enjoy better WordPress generators  Upgrade Now

So Our plugin file should look like this:

<?php
/*
Plugin Name: GWP mail BCC and CC
Plugin URI:
Description: A plugin to add bcc and cc email address to any mail sent by WordPress
Version: 1.0
Author: Ohad Raz
Author URI: https://generatewp.com
*/
/**
* GWP_bcc_cc_mail
*/
class GWP_bcc_cc_mail{
	
	/**
     * __construct
     * class constructor will set the needed filter and action hooks
     *
     */
	function __construct(){
		// Hook into the 'user_contactmethods' filter to add cc and bcc fields
		add_filter( 'user_contactmethods', array($this,'user_contactmethods' ));
		//hook into wp_mail to add cc and bcc as needed
		add_filter('wp_mail',array($this,'wp_mail'));

	}

	/**
	 * wp_mail 
	 * In this method we actuly add the cc and bcc address to the wp_mail call
	 * @param  array $args an associative array of mail arguments(to,subject,message,headers,attachments)
	 * @return array       
	 */
	function wp_mail($args){
		//get all emails that are already beeing sent to (users)
		$emails = $args['to'];
		//make sure we proccess them one by one
		$emails = explode(',', $emails);
		//loop over the emails and check if we need to add cc and bcc addresses
		foreach ($emails as $em) {
			//try to get the user id by the "to mail"
			$user = get_user_by( 'email', trim($em));
			if ($user){
				//get user ccs if exists
				$cc = get_user_meta( $user->ID, 'cc', true );
				if ( $cc ){
					//explode by comma "," to allow multiple cc addresses
					$ccs = explode(",", $cc);
					foreach ((array)$ccs as $cc_address) {
						$args['headers'][] = 'Cc: '.trim($cc_address);
					}
				}
				//get user bccs if exists
				$bcc = get_user_meta( $user->ID, 'bcc', true );
				if ( $bcc ){
					//explode by comma "," to allow multiple bcc addresses
					$bccs = explode(",", $bcc);
					foreach ((array)$bccs as $bcc_address) {
						$args['headers'][] = 'Bcc: '.trim($bcc_address);
					}
				}
			}
		}
	    return $args;
	}

	/**
	 * user_contactmethods
	 * @param  array $user_contact_method an associative array keyed by form field ids with human-readable text as values.
	 * @return array
	 */
	function user_contactmethods($user_contact_method){

		$user_contact_method['cc'] = __( 'CC email address (multiple: Comma separated emails)', 'GWP' );
		$user_contact_method['bcc'] = __( 'BCC email address (multiple: Comma separated emails)', 'GWP' );
		return $user_contact_method;
	}
}//end class
//instantiate the class
add_action( 'plugins_loaded', 'GWP_bcc_cc_mail_init' );
function GWP_bcc_cc_mail_init() {
    $GLOBALS['GWP_bcc_cc_mail'] = new GWP_bcc_cc_mail();
}

As always feedback and suggestions are more welcome.

Share on facebook
Share on twitter
Share on linkedin
Share on reddit
Share on whatsapp
Share on email
Ohad Raz

Ohad Raz

A WordPress Consultant, a plugins and themes developer,WordPress Development moderator and sometimes a WordPress core contributor.

12 Comments:

  • DavidM

    Beautifully written article, and that’s beside the fact of the code itself being beautifully written! Kudos for the excellent presentation. 🙂

    Reply

  • DaveDaveDave

    Superb and clean!

    Is it not possible to manipulate the script to be able to have individual emails sent for certain actions?

    e.g. new user registered, user gets usual email with credentials, but have the new user email sent to an alternate admin email address and not the main admin email.

    This would work really well for users who manage a website but do not need to be involved in the user approval/registration process.

    Reply

  • Kat

    That is an awesome and really helpful plugin Ohad and it was exactly what I needed!
    Thank you for sharing!

    Reply

  • Debbie

    This plug does just what I need. I’m using the meta user key in a formidable form. Hosever, when I update the form it gives this:

    Warning: explode() expects parameter 2 to be string, array given in …./wp-content/plugins/GWP-BCC-and-CC-email/gwp_bcc_cc_mail.php on line 38

    Warning: Invalid argument supplied for foreach() in …./wp-content/plugins/GWP-BCC-and-CC-email/gwp_bcc_cc_mail.php on line 40

    Thoughts?

    Reply

  • rolando

    with all these codes entered plugin super good, only to send the cc and bcc not sending me this after such step must be a more codes?

    Reply

  • danhoat

    I have just build this plugin and use can use this to add one or multiple cc email via dashboard.

    Reply

  • Vitaliy

    Installed this plugin and registered in the user’s settings an additional email. When you add a comment to the entry, error 500 occurs. The comment is added, but notification to the mail does not come at all. WP 4.8.1 version. Help please!

    Reply

  • ultradeluxxe

    Any Chance this can be updated for more modern WP/WC versions?

    Reply

  • kai

    Hi, Ohad… This is nice post! Thanks and appreciate you wrote this post and helping me a lot!

    Reply

  • Ihuusu

    That is an awesome and really helpful plugin Ohad and it was exactly what I needed!
    Thank you for sharing!

    Reply

  • cks

    Finally! I found this, was search through the google.. this is useful and helpful. Thanks Ohad!

    Reply

Leave a Reply

Subscribe to our Blog

Receive email notifications when new blog posts are published.