# Send Emails in the Background

> Queues emails sent by WordPress and plugins and sends them a few seconds later through WP-Cron, so form submissions, orders and registrations no longer wait for the mail server.

- Type: PHP
- Runs: Run everywhere
- Category: [Performance](https://wpide.com/library/category/performance/)
- Tags: email, cron, speed
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/perf-send-emails-in-background/

## Code

```php
add_filter( 'pre_wp_mail', function ( $return, $atts ) {
    if ( null !== $return || ! empty( $GLOBALS['wpide_mail_sending'] ) || ! empty( $atts['attachments'] ) || wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
        return $return;
    }

    $queue   = (array) get_option( 'wpide_mail_queue', array() );
    $queue[] = array(
        'to'      => $atts['to'],
        'subject' => $atts['subject'],
        'message' => $atts['message'],
        'headers' => $atts['headers'],
    );
    update_option( 'wpide_mail_queue', $queue, false );

    if ( ! wp_next_scheduled( 'wpide_send_mail_queue' ) ) {
        wp_schedule_single_event( time() + 5, 'wpide_send_mail_queue' );
    }

    return true;
}, 99, 2 );

add_action( 'wpide_send_mail_queue', function () {
    $queue = (array) get_option( 'wpide_mail_queue', array() );
    delete_option( 'wpide_mail_queue' );

    $GLOBALS['wpide_mail_sending'] = true;
    foreach ( $queue as $mail ) {
        if ( ! empty( $mail['to'] ) ) {
            wp_mail( $mail['to'], $mail['subject'], $mail['message'], $mail['headers'] );
        }
    }
    unset( $GLOBALS['wpide_mail_sending'] );
} );
```

## Notes

Emails with attachments are sent immediately, because temporary attachment files may be gone later; make sure WP-Cron runs reliably.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Send Emails in the Background" 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/
