WP-CLI Command to Send a Test Email
Adds "wp wpide-mail test [email protected]" to WP-CLI, which sends a test email and prints the exact error if it fails, handy on servers without admin access.
Opens WPIDE on
Code
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 [email protected]' );
}
$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 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.