| @@ -51,14 +51,40 @@ | ||
| 51 | 51 | 'Reply-To: ' . $from . "\r\n", |
| 52 | 52 | 'Content-Type: text/html; charset=UTF-8', |
| 53 | 53 | ]; |
| 54 | 54 | |
| 55 | - $sent = wp_mail($to, $subject, $message, $headers); | |
| 56 | - | |
| 57 | - if(!$sent){ | |
| 58 | - $error_message = error_get_last(); | |
| 59 | - $error_message = str_contains($error_message['message'] ?? '', 'Failed to connect to mailserver')? __( 'Failed to connect to mailserver', 'emailkit' ) : __( 'Failed to send the test email.', 'emailkit' ); | |
| 60 | - } | |
| 55 | + $mail_error = null; | |
| 56 | + add_action( 'wp_mail_failed', function( \WP_Error $wp_error ) use ( &$mail_error ) { | |
| 57 | + $mail_error = $wp_error; | |
| 58 | + } ); | |
| 59 | + | |
| 60 | + $sent = wp_mail( $to, $subject, $message, $headers ); | |
| 61 | + | |
| 62 | + if ( ! $sent ) { | |
| 63 | + $error_message = __( 'Failed to send the test email. Please configure an SMTP plugin.', 'emailkit' ); | |
| 64 | + | |
| 65 | + if ( $mail_error instanceof \WP_Error ) { | |
| 66 | + $raw = $mail_error->get_error_message(); | |
| 67 | + | |
| 68 | + $error_map = [ | |
| 69 | + 'Could not instantiate mail function' => __( 'Mail server is not configured on this server. Please use an SMTP plugin.', 'emailkit' ), | |
| 70 | + 'SMTP connect() failed' => __( 'Failed to connect to the SMTP server. Please check your SMTP settings.', 'emailkit' ), | |
| 71 | + 'Failed to connect to mailserver' => __( 'Failed to connect to the mail server. Please check your SMTP host and port.', 'emailkit' ), | |
| 72 | + 'Could not connect to SMTP host' => __( 'Could not connect to the SMTP host. Please verify your SMTP settings.', 'emailkit' ), | |
| 73 | + 'SMTP Error: Could not authenticate' => __( 'SMTP authentication failed. Please check your username and password.', 'emailkit' ), | |
| 74 | + 'Invalid address' => __( 'The recipient email address is invalid. Please enter a valid email.', 'emailkit' ), | |
| 75 | + 'Connection refused' => __( 'Connection to the mail server was refused. Please check your SMTP host and port.', 'emailkit' ), | |
| 76 | + 'Connection timed out' => __( 'Connection to the mail server timed out. Please check your SMTP host and port.', 'emailkit' ), | |
| 77 | + ]; | |
| 78 | + | |
| 79 | + foreach ( $error_map as $keyword => $friendly_message ) { | |
| 80 | + if ( str_contains( $raw, $keyword ) ) { | |
| 81 | + $error_message = $friendly_message; | |
| 82 | + break; | |
| 83 | + } | |
| 84 | + } | |
| 85 | + } | |
| 86 | + } | |
| 61 | 87 | |
| 62 | 88 | |
| 63 | 89 | if ($sent) { |
| 64 | 90 | return [ |