# WP-CLI Command to Send a Test Email

> Adds "wp wpide-mail test you@example.com" to WP-CLI, which sends a test email and prints the exact error if it fails, handy on servers without admin access.

- Type: PHP
- Runs: Run everywhere
- Category: [Email](https://wpide.com/library/category/email/)
- Tags: email, wp-cli, debugging
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/email-wp-cli-test-command/

## Code

```php
if ( defined( 'WP_CLI' ) && WP_CLI && class_exists( 'WP_CLI' ) ) {
    WP_CLI::add_command( 'wpide-mail test', function ( $args, $assoc ) {
        $to = isset( $args[0] ) ? sanitize_email( $args[0] ) : '';

        if ( ! is_email( $to ) ) {
            WP_CLI::error( 'Please pass a valid email address, e.g. wp wpide-mail test you@example.com' );
        }

        $error = '';
        $catch = function ( $wp_error ) use ( &$error ) {
            $error = $wp_error->get_error_message();
        };
        add_action( 'wp_mail_failed', $catch );

        $subject = isset( $assoc['subject'] ) ? sanitize_text_field( $assoc['subject'] ) : 'Test email from ' . wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
        $sent    = wp_mail( $to, $subject, 'This is a test email sent with WP-CLI from ' . home_url() . ' at ' . wp_date( 'Y-m-d H:i:s' ) . '.' );

        remove_action( 'wp_mail_failed', $catch );

        if ( $sent ) {
            WP_CLI::success( "Email handed to the mail server for $to." );
        } else {
            WP_CLI::error( 'Sending failed: ' . ( $error ? $error : 'unknown error' ) );
        }
    } );
}
```

## Notes

Add --subject="..." to change the subject; the command only exists when WP-CLI is running.

## How to use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "WP-CLI Command to Send a Test 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/
