} */ public static function send( string $to ): array { $error = ''; $replies = array(); // phpcs:disable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase -- PHPMailer's own property names. $capture = static function ( \WP_Error $failure ) use ( &$error ): void { $error = $failure->get_error_message(); }; $listen = static function ( $phpmailer ) use ( &$replies ): void { if ( ! $phpmailer instanceof \PHPMailer\PHPMailer\PHPMailer || 'smtp' !== $phpmailer->Mailer ) { return; } $phpmailer->SMTPDebug = 2; $phpmailer->Debugoutput = static function ( $line ) use ( &$replies ): void { $line = trim( (string) $line ); if ( str_contains( $line, 'SERVER -> CLIENT:' ) ) { $replies[] = sanitize_text_field( (string) preg_replace( '/^.*?SERVER -> CLIENT:\s*/', '', $line ) ); } }; }; // phpcs:enable WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase add_action( 'wp_mail_failed', $capture ); add_action( 'phpmailer_init', $listen, 99 ); $sent = wp_mail( $to, /* translators: %s: site name. */ sprintf( __( 'Test email from %s', 'forensix-digital' ), wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES ) ), __( 'This is a test message from Forensix Digital. If you can read it, your site can send email.', 'forensix-digital' ) ); remove_action( 'wp_mail_failed', $capture ); remove_action( 'phpmailer_init', $listen, 99 ); $result = array( 'ok' => $sent, 'message' => $sent /* translators: %s: email address. */ ? sprintf( __( 'The test email was handed over for delivery to %s. Check that inbox, and the spam folder.', 'forensix-digital' ), $to ) : self::explain( $error ), 'details' => array_slice( array_values( array_filter( $replies ) ), -4 ), ); update_option( self::LAST, array( 'time' => time(), 'ok' => $sent, ), false ); return $result; } /** * A plain-language reason for a failure. * * @param string $error The mailer's message. */ public static function explain( string $error ): string { $lower = strtolower( $error ); if ( str_contains( $lower, 'could not authenticate' ) || str_contains( $lower, 'authentication' ) ) { return __( 'The mail server did not accept the user name or password. Check both, and use an app password if your provider needs one.', 'forensix-digital' ); } if ( str_contains( $lower, 'connect' ) ) { return __( 'Your site could not reach the mail server. Check the server name, the port and the encryption. Some hosts block outgoing mail ports; your host can tell you.', 'forensix-digital' ); } if ( str_contains( $lower, 'from' ) && str_contains( $lower, 'address' ) ) { return __( 'The mail server did not accept the sender address. Use an address that belongs to your mail account.', 'forensix-digital' ); } return __( 'The email could not be sent. Check the settings and try again.', 'forensix-digital' ); } }