Skip to content

Instantly share code, notes, and snippets.

@danielbachhuber
Created July 30, 2019 22:34
Show Gist options
  • Save danielbachhuber/93113d127585f7b753a578b55d3a9e3c to your computer and use it in GitHub Desktop.
Save danielbachhuber/93113d127585f7b753a578b55d3a9e3c to your computer and use it in GitHub Desktop.
Splits wp_mail() with more than 40 bcc into multiple batches
<?php
/**
* Splits a wp_mail() call with more than 40 bcc
* headers into multiple batches.
*
* Postmark only accepts 50 bcc, so this ensures the API call doesn't fail.
*
* @param array $args Original arguments passed to wp_mail().
* @return
*/
add_filter( 'wp_mail', function( $args ) {
// Scenarios we can't process.
if ( empty( $args['headers'] )
|| ! is_array( $args['headers'] )
|| count( $args['headers'] ) < 40 ) {
return $args;
}
// Capture all of the existing bcc headers.
$mod_headers = $args['headers'];
$bcc_headers = [];
foreach ( $mod_headers as $i => $header ) {
if ( 0 === stripos( $header, 'bcc:' ) ) {
unset( $mod_headers[ $i ] );
$bcc_headers[] = $header;
}
}
// Don't need to modify if there are less than 40 recipients.
if ( count( $bcc_headers ) < 40 ) {
return $args;
}
// Break the bcc emails into chunks of less than 40.
$mod_headers = array_values( $mod_headers );
foreach ( array_chunk( $bcc_headers, 40 ) as $i => $chunk ) {
// Keep the first chunk for the original send.
if ( 0 === $i ) {
$first_chunk = $chunk;
continue;
}
// Send out the chunk.
$chunk_headers = array_merge( $mod_headers, $chunk );
wp_mail(
$args['to'],
$args['subject'],
$args['message'],
$chunk_headers,
$args['attachments']
);
}
// Use the $first_chunk for the original send.
$args['headers'] = array_merge( $mod_headers, $first_chunk );
return $args;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment