# 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.

- Type: PHP
- Runs: Run everywhere
- Category: [Email](https://wpide.com/library/category/email/)
- Tags: email, security, limits
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/email-recipient-cap/

## Code

```php
$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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Limit the Number of Recipients per Email" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
