Limit the Number of Recipients per Email
Refuses to send any single email to more than a set number of recipients across To, CC and BCC, which stops a compromised form or plugin from blasting your contacts.
Opens WPIDE on
Code
$wpide_max_recipients = 20;
add_filter( 'pre_wp_mail', function ( $return, $atts ) use ( $wpide_max_recipients ) {
if ( null !== $return ) {
return $return;
}
$count = count( array_filter( is_array( $atts['to'] ) ? $atts['to'] : explode( ',', (string) $atts['to'] ) ) );
$headers = is_array( $atts['headers'] ) ? $atts['headers'] : explode( "\n", (string) $atts['headers'] );
foreach ( $headers as $line ) {
if ( preg_match( '/^\s*(cc|bcc)\s*:(.*)$/i', (string) $line, $m ) ) {
$count += count( array_filter( array_map( 'trim', explode( ',', $m[2] ) ) ) );
}
}
if ( $count > $wpide_max_recipients ) {
do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', sprintf( 'Blocked: %d recipients exceeds the limit of %d.', $count, $wpide_max_recipients ), $atts ) );
return false;
}
return $return;
}, 2, 2 );
Notes
Raise the cap if you legitimately email larger groups; blocked emails are reported as failures.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.