'WP Mail SMTP', 'wp-mail-smtp-pro/wp_mail_smtp.php' => 'WP Mail SMTP Pro', 'fluent-smtp/fluent-smtp.php' => 'FluentSMTP', 'post-smtp/postman-smtp.php' => 'Post SMTP', 'easy-wp-smtp/easy-wp-smtp.php' => 'Easy WP SMTP', 'wp-smtp/wp-smtp.php' => 'WP SMTP', 'smtp-mailer/main.php' => 'SMTP Mailer', 'gmail-smtp/main.php' => 'Gmail SMTP', 'wp-mail-bank/wp-mail-bank.php' => 'Mail Bank', 'sendgrid-email-delivery-simplified/wpsendgrid.php' => 'SendGrid', 'mailgun/mailgun.php' => 'Mailgun', ]; public function __construct() { $this->settings = Plugin::get_settings( 'updates-and-notifications' ); add_filter( 'adminease_settings_fields', [ $this, 'adminease_settings_fields' ] ); add_action( 'adminease_after_child_field_render', [ $this, 'adminease_after_child_field_render' ] ); add_filter( 'adminease_validate_settings', [ $this, 'preserve_password_on_save' ], 20 ); add_filter( 'pre_update_option_adminease_settings', [ $this, 'preserve_password_on_update' ], 10, 2 ); if( empty( $this->settings['smtp_enabled'] ) ) { return; } add_action( 'admin_enqueue_scripts', [ $this, 'admin_enqueue_scripts' ] ); add_action( 'wp_ajax_adminease_smtp_test', [ $this, 'ajax_send_test_email' ] ); if( !$this->is_configured() ) { return; } add_action( 'phpmailer_init', [ $this, 'configure_phpmailer' ], 20 ); add_filter( 'wp_mail_from', [ $this, 'filter_mail_from' ], 20 ); add_filter( 'wp_mail_from_name', [ $this, 'filter_mail_from_name' ], 20 ); } /** * Adds the SMTP fields to the Email tab. They are still stored under updates-and-notifications. * * @param array $fields An array of existing settings fields, keyed by tab. * * @return array The modified array of settings fields. */ public function adminease_settings_fields( array $fields ): array { $fields['email']['fields'][] = [ 'type' => 'switch', 'id' => 'smtp-enabled', 'name' => 'adminease[updates-and-notifications][smtp_enabled]', 'value' => $this->settings['smtp_enabled'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input toggle-field', 'label' => __( 'Send email through SMTP', 'adminease' ), 'description' => __( 'Password resets that never arrive. Order confirmations that land in spam. That is what happens when WordPress sends mail by itself: the message goes out from an address nobody owns, with nothing to prove it came from you, and Gmail and Outlook treat it like junk from a stranger.

Turn this on and every email leaves through a real mailbox instead, one that is allowed to send on your behalf. Enter the details from your email provider, press Send Test Email, and watch the whole conversation with the mail server unfold line by line. You find out it works before your customers find out it does not.

💡 Not sure what to enter? Open What You Need just below for the exact settings for Gmail, Microsoft 365, Brevo, Mailgun and your own web host.', 'adminease' ), 'field_description' => $this->get_status_notice(), 'child_fields' => [ [ 'type' => 'text', 'id' => 'smtp-host', 'name' => 'adminease[updates-and-notifications][smtp_host]', 'value' => $this->settings['smtp_host'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'SMTP host', 'adminease' ), 'placeholder' => 'smtp.example.com', 'field_description' => __( 'The outgoing mail server address from your email provider, such as smtp.gmail.com or smtp.office365.com.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', 'autocomplete' => 'off', ], ], [ 'type' => 'select', 'id' => 'smtp-encryption', 'name' => 'adminease[updates-and-notifications][smtp_encryption]', 'value' => $this->get_encryption(), 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Encryption', 'adminease' ), 'field_description' => __( 'TLS goes with port 587 and SSL with port 465. Almost every provider wants TLS on 587. Only choose None if your provider explicitly tells you to, because the password is then sent unencrypted.', 'adminease' ), 'options' => [ self::ENCRYPTION_TLS => __( 'TLS (recommended)', 'adminease' ), self::ENCRYPTION_SSL => __( 'SSL', 'adminease' ), self::ENCRYPTION_NONE => __( 'None', 'adminease' ), ], 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'number', 'id' => 'smtp-port', 'name' => 'adminease[updates-and-notifications][smtp_port]', 'value' => $this->settings['smtp_port'] ?? self::DEFAULT_PORT, 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Port', 'adminease' ), 'field_description' => __( 'Usually 587 for TLS or 465 for SSL.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', 'min' => 1, 'max' => 65535, 'step' => 1, ], ], [ 'type' => 'switch', 'id' => 'smtp-auth', 'name' => 'adminease[updates-and-notifications][smtp_auth]', 'value' => $this->is_auth_enabled(), 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Use authentication', 'adminease' ), 'description' => __( 'Log in to the mail server with a username and password. Leave this on unless your provider tells you otherwise.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'text', 'id' => 'smtp-username', 'name' => 'adminease[updates-and-notifications][smtp_username]', 'value' => $this->settings['smtp_username'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'SMTP username', 'adminease' ), 'field_description' => __( 'Usually the full email address of the mailbox you are sending through.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', 'autocomplete' => 'off', ], ], [ 'type' => 'password', 'id' => 'smtp-password', 'name' => 'adminease[updates-and-notifications][smtp_password]', 'value' => '', 'placeholder' => $this->has_stored_password() ? '••••••••••••' : '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'SMTP password', 'adminease' ), 'field_description' => $this->get_password_field_description(), 'attributes' => [ 'data-parent' => 'smtp-enabled', 'autocomplete' => 'new-password', ], ], [ 'type' => 'text', 'id' => 'smtp-from-email', 'name' => 'adminease[updates-and-notifications][smtp_from_email]', 'value' => $this->settings['smtp_from_email'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'From address', 'adminease' ), 'placeholder' => get_option( 'admin_email' ), 'field_description' => __( 'The address your emails appear to come from. Most providers require this to be the mailbox you are logging in as, and will either reject the message or silently rewrite it otherwise. Leave empty to keep whatever address WordPress already uses.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'switch', 'id' => 'smtp-force-from-email', 'name' => 'adminease[updates-and-notifications][smtp_force_from_email]', 'value' => $this->settings['smtp_force_from_email'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Force the From address', 'adminease' ), 'description' => __( 'Use the address above for every email, replacing addresses set by other plugins. Leave this off and only the default WordPress address is replaced, so WooCommerce and contact form plugins keep sending as whatever they were configured to send as.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'text', 'id' => 'smtp-from-name', 'name' => 'adminease[updates-and-notifications][smtp_from_name]', 'value' => $this->settings['smtp_from_name'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'From name', 'adminease' ), 'placeholder' => get_bloginfo( 'name' ), 'field_description' => __( 'The sender name shown in the inbox. Leave empty to keep whatever name WordPress already uses.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'switch', 'id' => 'smtp-force-from-name', 'name' => 'adminease[updates-and-notifications][smtp_force_from_name]', 'value' => $this->settings['smtp_force_from_name'] ?? '', 'label_class' => 'pwp-switch', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Force the From name', 'adminease' ), 'description' => __( 'Use the name above for every email, replacing names set by other plugins.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'text', 'id' => 'smtp-test-recipient', 'name' => 'adminease[updates-and-notifications][smtp_test_recipient]', 'value' => $this->settings['smtp_test_recipient'] ?? '', 'label_class' => 'pwp-field-label', 'input_class' => 'pwp-field-input', 'wrapper_class' => 'form-group-child', 'label' => __( 'Send a test email to', 'adminease' ), 'placeholder' => get_option( 'admin_email' ), 'field_description' => __( 'Leave empty to use your site administration email address.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', ], ], [ 'type' => 'button', 'id' => 'smtp-test-submit', 'input_class' => 'pwp-btn pwp-btn-primary', 'label' => __( 'Send Test Email', 'adminease' ), 'field_description' => __( 'Save your settings first. The test reports exactly what the mail server said, so a wrong password or a blocked port can be read rather than guessed at.', 'adminease' ), 'attributes' => [ 'data-parent' => 'smtp-enabled', 'role' => 'button', ], ], ], ]; return $fields; } /** * Renders the test result panel directly underneath the test button. * * It hangs off the button rather than off the parent field because * adminease_after_field_render fires past the whole explanation column, * which would put the result a screen and a half below the button that * produced it. * * @param array $child_field The child field data array, which contains attributes such as the field ID. * * @return void */ public function adminease_after_child_field_render( array $child_field ): void { if( 'smtp-test-submit' !== ( $child_field['id'] ?? '' ) ) { return; } if( !current_user_can( 'manage_options' ) ) { return; } if( !file_exists( ADMINEASE_DIR . 'partials/smtp-test.php' ) ) { return; } include ADMINEASE_DIR . 'partials/smtp-test.php'; } /** * Enqueues the test-send script on the AdminEase dashboard. * * @param string $hook The current admin page hook. * * @return void */ public function admin_enqueue_scripts( string $hook ): void { if( 'toplevel_page_adminease' !== $hook ) { return; } if( !current_user_can( 'manage_options' ) ) { return; } wp_enqueue_script( ADMINEASE_NAME . 'Smtp', ADMINEASE_PLUGIN_URL . 'assets/js/AdminEaseSmtp.js', [ 'jquery', ADMINEASE_NAME ], filemtime( ADMINEASE_DIR . 'assets/js/AdminEaseSmtp.js' ), true ); wp_localize_script( ADMINEASE_NAME . 'Smtp', ADMINEASE_NAME . 'SmtpAjaxObj', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'security' => wp_create_nonce( 'adminease_smtp_nonce' ), 'i18n' => [ 'sending' => esc_html__( 'Sending...', 'adminease' ), 'sent' => esc_html__( 'Test email sent', 'adminease' ), 'error' => esc_html__( 'An error occurred. Refresh the page and try again.', 'adminease' ), /* translators: %1$d: HTTP status code, %2$s: message returned by the server */ 'httpError' => esc_html__( 'Request failed (HTTP %1$d): %2$s', 'adminease' ), /* translators: %d: HTTP status code returned by the gateway */ 'gatewayError' => esc_html__( 'The mail server took too long to answer and the request timed out at the gateway (HTTP %d). This usually means the port is blocked by your host.', 'adminease' ), 'networkError' => esc_html__( 'The server could not be reached. Check your connection and try again.', 'adminease' ), ], 'config' => [ 'tls' => self::ENCRYPTION_TLS, 'ssl' => self::ENCRYPTION_SSL, 'tlsPort' => self::PORT_TLS, 'sslPort' => self::PORT_SSL, 'defaultPort' => self::DEFAULT_PORT, ], ] ); } /** * Points PHPMailer at the configured SMTP server. * * @param object $phpmailer The PHPMailer instance, passed by reference by WordPress. * * @return void */ public function configure_phpmailer( $phpmailer ): void { $phpmailer->isSMTP(); $phpmailer->Host = trim( (string) ( $this->settings['smtp_host'] ?? '' ) ); $phpmailer->Port = $this->get_port(); $phpmailer->Timeout = $this->get_timeout(); $encryption = $this->get_encryption(); if( self::ENCRYPTION_NONE === $encryption ) { $phpmailer->SMTPSecure = ''; $phpmailer->SMTPAutoTLS = false; } else { $phpmailer->SMTPSecure = $encryption; $phpmailer->SMTPAutoTLS = true; } $phpmailer->SMTPAuth = $this->is_auth_enabled(); if( $phpmailer->SMTPAuth ) { $phpmailer->Username = (string) ( $this->settings['smtp_username'] ?? '' ); $phpmailer->Password = $this->get_password(); } do_action( 'adminease_smtp_phpmailer_init', $phpmailer, $this->settings ); } /** * Replaces the From address of outgoing mail. * * Without "force", only WordPress's own wordpress@yoursite placeholder is replaced. * Anything else was chosen deliberately by core, a theme or another plugin, and * overriding it unconditionally rewrites WooCommerce's per-email sender. * * @param string $from_email The address WordPress resolved for this message. * * @return string The address to send as. */ public function filter_mail_from( $from_email ) { $configured = trim( (string) ( $this->settings['smtp_from_email'] ?? '' ) ); if( !is_email( $configured ) ) { return $from_email; } if( !empty( $this->settings['smtp_force_from_email'] ) ) { return $configured; } return $this->is_default_from_email( (string) $from_email ) ? $configured : $from_email; } /** * Replaces the sender name of outgoing mail, on the same terms as the address. * * @param string $from_name The name WordPress resolved for this message. * * @return string The name to send as. */ public function filter_mail_from_name( $from_name ) { $configured = trim( (string) ( $this->settings['smtp_from_name'] ?? '' ) ); if( '' === $configured ) { return $from_name; } if( !empty( $this->settings['smtp_force_from_name'] ) ) { return $configured; } return 'WordPress' === $from_name ? $configured : $from_name; } /** * Sends a test email and returns what the mail server said about it. * * Every message here reaches the browser as JSON and is written to the page with * jQuery's text(), which escapes on its own. Escaping again on this side would show * the entities rather than the characters, so these strings are translated only. * * @return void */ public function ajax_send_test_email(): void { if( !isset( $_POST['security'] ) || !wp_verify_nonce( sanitize_key( wp_unslash( $_POST['security'] ) ), 'adminease_smtp_nonce' ) ) { wp_send_json_error( new WP_Error( 'security_error', __( 'Security check failed. Refresh the page and try again.', 'adminease' ) ), 403 ); } if( !current_user_can( 'manage_options' ) ) { wp_send_json_error( new WP_Error( 'permissions', __( 'You do not have sufficient permissions to perform this action', 'adminease' ) ), 403 ); } $recipient = isset( $_POST['recipient'] ) ? sanitize_email( wp_unslash( $_POST['recipient'] ) ) : ''; if( '' === $recipient ) { $recipient = (string) get_option( 'admin_email' ); } if( !is_email( $recipient ) ) { wp_send_json_error( [ 'message' => __( 'Please enter a valid email address to send the test to.', 'adminease' ) ] ); } $missing = $this->get_missing_requirements(); if( !empty( $missing ) ) { wp_send_json_error( [ 'message' => sprintf( /* translators: %s: comma separated list of setting names. */ __( 'Fill in %s and save the settings before sending a test.', 'adminease' ), implode( ', ', $missing ) ), ] ); } $debug_settings = Plugin::get_settings( 'debug' ); if( !empty( $debug_settings['email_log_disable_sending'] ) ) { wp_send_json_error( [ 'message' => __( 'Email Log has "Disable Email Sending" switched on, so nothing leaves the site and a test cannot reach your mail server. Turn that setting off and try again.', 'adminease' ) ] ); } $result = $this->send_test_email( $recipient ); if( true !== $result['sent'] ) { wp_send_json_error( [ 'message' => $result['message'], 'transcript' => $result['transcript'], ] ); } wp_send_json_success( [ 'message' => $result['message'], 'transcript' => $result['transcript'], ] ); } /** * Runs the test send with the SMTP conversation captured. * * @param string $recipient The address to send the test to. * * @return array { * @type bool $sent Whether wp_mail() reported success. * @type string $message A readable summary for the admin. * @type array $transcript The redacted SMTP conversation. * } */ private function send_test_email( string $recipient ): array { $this->testing = true; $this->debug_lines = []; $this->test_error = null; $this->effective_config = []; $this->transcript_truncated = false; add_action( 'phpmailer_init', [ $this, 'enable_debug_output' ], 999 ); add_action( 'phpmailer_init', [ $this, 'snapshot_effective_config' ], PHP_INT_MAX ); add_action( 'wp_mail_failed', [ $this, 'capture_test_failure' ] ); add_filter( 'adminease_email_failure_alert_should_send', '__return_false', 99 ); $sent = wp_mail( $recipient, $this->get_test_subject(), $this->get_test_message() ); remove_filter( 'adminease_email_failure_alert_should_send', '__return_false', 99 ); remove_action( 'wp_mail_failed', [ $this, 'capture_test_failure' ] ); remove_action( 'phpmailer_init', [ $this, 'snapshot_effective_config' ], PHP_INT_MAX ); remove_action( 'phpmailer_init', [ $this, 'enable_debug_output' ], 999 ); $this->reset_debug_output(); $this->testing = false; if( $sent ) { $message = sprintf( /* translators: %s: the address the test email was sent to. */ __( 'The mail server accepted the message and it was sent to %s. If it does not arrive, check the spam folder and confirm the From address belongs to the mailbox you are sending through.', 'adminease' ), $recipient ); } elseif( $this->test_error instanceof WP_Error ) { $message = $this->test_error->get_error_message(); } else { $message = __( 'The email could not be sent and the mail server gave no reason.', 'adminease' ); } $interference = $this->get_interference_warning(); if( '' !== $interference ) { $message = $interference . ' ' . $message; } $transcript = $this->redact_transcript( $this->debug_lines ); if( $this->transcript_truncated ) { $transcript[] = sprintf( /* translators: %d: the number of lines shown above. */ __( '[Cut short after %d lines. The conversation carried on past this point.]', 'adminease' ), self::MAX_TRANSCRIPT_LINES ); } $this->debug_lines = []; $this->test_error = null; $this->effective_config = []; return [ 'sent' => (bool) $sent, 'message' => $message, 'transcript' => $transcript, ]; } /** * Takes PHPMailer back out of debug mode once the test send is over. * * WordPress keeps one PHPMailer instance in a global for the whole request and clears * only the recipients, attachments, headers and body between calls, so removing the * phpmailer_init listener does not undo the properties that listener already wrote. * Left as it is, the mailer stays in debug mode for the rest of the request, and any * later code that restores the default Debugoutput would echo the SMTP conversation * straight into the response. * * @return void */ private function reset_debug_output(): void { global $phpmailer; if( !is_object( $phpmailer ) ) { return; } $phpmailer->SMTPDebug = 0; $phpmailer->Debugoutput = 'echo'; } /** * Reports a test that did not go where the saved settings say it should have. * * KNOWN_MAILER_PLUGINS can only name the plugins listed in it. This reads what the * mailer was actually holding when the message went out, so an unlisted plugin, a * custom snippet or a mailer that bypasses SMTP entirely is reported all the same. * * @return string A sentence to put in front of the result, or an empty string when * nothing interfered. */ private function get_interference_warning(): string { if( empty( $this->effective_config ) ) { return __( 'Something answered for the send before it ever reached the mail layer, so your SMTP server was not contacted and this result says nothing about it. A mail plugin that delivers through an API rather than SMTP does exactly this.', 'adminease' ); } if( 'smtp' !== ( $this->effective_config['mailer'] ?? '' ) ) { return __( 'Something switched sending away from SMTP after AdminEase had set it up, so this did not test your mail server. Leave only one mail plugin switched on.', 'adminease' ); } $host = trim( (string) ( $this->settings['smtp_host'] ?? '' ) ); if( 0 === strcasecmp( $host, (string) ( $this->effective_config['host'] ?? '' ) ) && $this->get_port() === ( $this->effective_config['port'] ?? 0 ) ) { return ''; } return sprintf( /* translators: 1: the mail server that was actually used, 2: the port that was actually used. */ __( 'Something changed the outgoing mail settings after AdminEase had applied them, so the message went to %1$s on port %2$d rather than the server saved here. Leave only one mail plugin switched on.', 'adminease' ), $this->effective_config['host'], $this->effective_config['port'] ); } /** * Turns on PHPMailer's server-level debug output for the test send only. * * @param object $phpmailer The PHPMailer instance, passed by reference by WordPress. * * @return void */ public function enable_debug_output( $phpmailer ): void { if( !$this->testing ) { return; } $phpmailer->SMTPDebug = 2; $phpmailer->Debugoutput = function( $line ) { if( count( $this->debug_lines ) >= self::MAX_TRANSCRIPT_LINES ) { $this->transcript_truncated = true; return; } $this->debug_lines[] = rtrim( (string) $line ); }; } /** * Records what PHPMailer is holding at the moment the test message goes out. * * Hooked last of everything on phpmailer_init so that a plugin which reconfigures the * mailer after this one is what gets recorded here, which is the whole point of it. * * @param object $phpmailer The PHPMailer instance, passed by reference by WordPress. * * @return void */ public function snapshot_effective_config( $phpmailer ): void { if( !$this->testing ) { return; } $this->effective_config = [ 'mailer' => strtolower( (string) $phpmailer->Mailer ), 'host' => trim( (string) $phpmailer->Host ), 'port' => (int) $phpmailer->Port, ]; } /** * Keeps the failure reported during a test send so the real reason can be shown. * * @param WP_Error $error The error object passed by the wp_mail_failed action. * * @return void */ public function capture_test_failure( $error ): void { if( !$this->testing || !$error instanceof WP_Error ) { return; } $this->test_error = $error; } /** * Removes credentials from the SMTP conversation before it reaches the browser. * * A server-level transcript contains the login exchange, so shipping it unmodified * puts the base64 encoded username and password on the settings screen and into * whatever the admin then pastes into a support thread. * * @param array $lines The captured conversation. * * @return array The conversation with the credentials masked. */ private function redact_transcript( array $lines ): array { $mask = '[redacted]'; $secrets = []; foreach( [ (string) ( $this->settings['smtp_username'] ?? '' ), $this->get_password() ] as $secret ) { if( '' === $secret ) { continue; } $secrets[] = $secret; $secrets[] = base64_encode( $secret ); } $redacted = []; $client_lines_left = 0; foreach( $lines as $line ) { $line = (string) $line; if( !empty( $secrets ) ) { $line = str_replace( $secrets, $mask, $line ); } if( 0 < $client_lines_left && false !== strpos( $line, 'CLIENT -> SERVER' ) ) { $line = 'CLIENT -> SERVER: ' . $mask; $client_lines_left--; } if( false !== stripos( $line, 'AUTH LOGIN' ) ) { $client_lines_left = 2; } else { $line = (string) preg_replace( '/(AUTH\s+(?:PLAIN|CRAM-MD5|XOAUTH2)\s+)\S+/i', '$1' . $mask, $line ); } $redacted[] = $this->truncate_line( $line ); } return $redacted; } /** * Caps the length of one transcript line. * * Called after the masking, never before it, so that a credential cannot be split * across the cut and survive in the part that is kept. * * @param string $line The redacted line. * * @return string The line, shortened when it runs past the cap. */ private function truncate_line( string $line ): string { $length = function_exists( 'mb_strlen' ) ? mb_strlen( $line ) : strlen( $line ); if( self::MAX_TRANSCRIPT_LINE_LENGTH >= $length ) { return $line; } $line = function_exists( 'mb_substr' ) ? mb_substr( $line, 0, self::MAX_TRANSCRIPT_LINE_LENGTH ) : substr( $line, 0, self::MAX_TRANSCRIPT_LINE_LENGTH ); return $line . ' [...]'; } /** * Builds the test email subject line. * * @return string The subject line. */ private function get_test_subject(): string { $blogname = wp_specialchars_decode( (string) get_option( 'blogname' ), ENT_QUOTES ); /* translators: %s: site name. */ return sprintf( __( '[%s] AdminEase SMTP test', 'adminease' ), $blogname ); } /** * Builds the plain text test email body. * * @return string The message body. */ private function get_test_message(): string { $lines = [ sprintf( /* translators: %s: site URL. */ __( 'This is a test email from %s. If you are reading it, your SMTP settings are working.', 'adminease' ), home_url() ), '', /* translators: %s: SMTP server address. */ sprintf( __( 'Server: %s', 'adminease' ), (string) ( $this->settings['smtp_host'] ?? '' ) ), /* translators: %d: SMTP port number. */ sprintf( __( 'Port: %d', 'adminease' ), $this->get_port() ), /* translators: %s: encryption method, for example TLS. */ sprintf( __( 'Encryption: %s', 'adminease' ), strtoupper( $this->get_encryption() ) ), '', sprintf( /* translators: %s: date and time the test was sent, in the site timezone. */ __( 'Sent: %s', 'adminease' ), wp_date( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) ) ), ]; return implode( "\n", $lines ); } /** * Keeps the stored SMTP password across a settings save. * * The field is always rendered empty so the secret is never written into the page * source, and ajax_save_settings() replaces the whole option with what was posted, * so without this every save of any setting on the dashboard would blank it. * * @param mixed $sanitized_settings The full sanitized settings array. * * @return mixed The settings array with the password resolved. */ public function preserve_password_on_save( $sanitized_settings ) { if( !is_array( $sanitized_settings ) || !isset( $sanitized_settings['updates-and-notifications'] ) || !is_array( $sanitized_settings['updates-and-notifications'] ) ) { return $sanitized_settings; } $existing = Plugin::get_settings( 'updates-and-notifications' ); $sanitized_settings['updates-and-notifications']['smtp_password'] = $this->resolve_password_for_storage( $sanitized_settings['updates-and-notifications']['smtp_password'] ?? '', $existing['smtp_password'] ?? '' ); return $sanitized_settings; } /** * Applies the same rule to any code path that writes the option directly. * * @param mixed $new_value The settings array about to be saved. * @param mixed $old_value The existing settings array. * * @return mixed The settings array with the password resolved. */ public function preserve_password_on_update( $new_value, $old_value ) { if( !is_array( $new_value ) || !isset( $new_value['updates-and-notifications'] ) || !is_array( $new_value['updates-and-notifications'] ) ) { return $new_value; } $existing = is_array( $old_value ) ? ( $old_value['updates-and-notifications']['smtp_password'] ?? '' ) : ''; $new_value['updates-and-notifications']['smtp_password'] = $this->resolve_password_for_storage( $new_value['updates-and-notifications']['smtp_password'] ?? '', $existing ); return $new_value; } /** * Decides what the stored password value should become. * * - Blank submission with something already stored → keep what is stored. * - Already encrypted submission → keep as-is. * - Anything else → encrypt it. * * @param mixed $submitted The value that arrived with the save. * @param mixed $existing The value currently stored. * * @return string The value to store. */ private function resolve_password_for_storage( $submitted, $existing ): string { $submitted = (string) $submitted; $existing = (string) $existing; if( '' === $submitted ) { return $existing; } if( $this->is_encrypted( $submitted ) ) { return $submitted; } return $this->encrypt( $submitted ); } /** * Resolves the password handed to PHPMailer. * * A constant in wp-config.php wins over the stored value, so a site that would * rather keep the credential out of the database entirely can define it by hand. * * The result is held for the request because $this->settings is read once in the * constructor and never reloaded, and the callers ask repeatedly: once on every page * load through is_configured(), and again for each notice on the settings screen. * * @return string The plaintext password, or an empty string when there is none. */ private function get_password(): string { if( null !== $this->password_cache ) { return $this->password_cache; } if( defined( 'ADMINEASE_SMTP_PASS' ) && '' !== (string) ADMINEASE_SMTP_PASS ) { $this->password_cache = (string) ADMINEASE_SMTP_PASS; return $this->password_cache; } $this->password_cache = $this->decrypt( (string) ( $this->settings['smtp_password'] ?? '' ) ); return $this->password_cache; } /** * Whether a usable password is available, for the placeholder and the field help. * * This reads the decrypted value rather than the stored one. A value that no longer * decrypts is not a password the site can send with, and counting it as one is what * let the field claim a password was saved while the toggle warned it was missing. * * @return bool True when a readable password is stored or defined as a constant. */ private function has_stored_password(): bool { return '' !== $this->get_password(); } /** * Whether a password is stored but can no longer be read. * * Rotating the site salts changes the key, which leaves a value in the database that * nothing can decrypt. Unexplained it is a dead end: the field looks filled in, every * email fails to authenticate, and leaving the field empty on save keeps the * unreadable value exactly where it is. * * @return bool True when a stored value exists and decrypting it produced nothing. */ private function has_unreadable_password(): bool { if( defined( 'ADMINEASE_SMTP_PASS' ) && '' !== (string) ADMINEASE_SMTP_PASS ) { return false; } return '' !== (string) ( $this->settings['smtp_password'] ?? '' ) && '' === $this->get_password(); } /** * Encrypts a password for storage. * * This is obfuscation rather than protection: the key is derived from the site * salts, so anyone holding both the database and the filesystem holds both halves. * What it buys is that a database dump on its own does not hand over the mailbox. * * @param string $plaintext The password as typed. * * @return string The value to store. */ private function encrypt( string $plaintext ): string { if( '' === $plaintext ) { return ''; } if( !$this->has_sodium() ) { return self::CIPHER_PREFIX_PLAIN . base64_encode( $plaintext ); } try { $nonce = random_bytes( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ); $ciphertext = sodium_crypto_secretbox( $plaintext, $nonce, $this->get_key() ); } catch( \Exception $e ) { return self::CIPHER_PREFIX_PLAIN . base64_encode( $plaintext ); } return self::CIPHER_PREFIX_SODIUM . base64_encode( $nonce . $ciphertext ); } /** * Reverses encrypt(). * * Rotating the site salts changes the key, so a previously stored password stops * decrypting and this returns an empty string. That surfaces as an authentication * failure the test tool reports, and is fixed by entering the password again. * * @param string $stored The value read from the settings. * * @return string The plaintext password, or an empty string when it cannot be read. */ private function decrypt( string $stored ): string { if( '' === $stored ) { return ''; } if( 0 === strpos( $stored, self::CIPHER_PREFIX_PLAIN ) ) { $decoded = base64_decode( substr( $stored, strlen( self::CIPHER_PREFIX_PLAIN ) ), true ); return false === $decoded ? '' : $decoded; } if( 0 !== strpos( $stored, self::CIPHER_PREFIX_SODIUM ) ) { return $stored; } if( !$this->has_sodium() ) { return ''; } $raw = base64_decode( substr( $stored, strlen( self::CIPHER_PREFIX_SODIUM ) ), true ); if( false === $raw || strlen( $raw ) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ) { return ''; } $plaintext = sodium_crypto_secretbox_open( substr( $raw, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ), substr( $raw, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ), $this->get_key() ); return false === $plaintext ? '' : $plaintext; } /** * Whether a stored value was written by encrypt(). * * @param string $value The value to test. * * @return bool True when the value carries one of the storage markers. */ private function is_encrypted( string $value ): bool { return 0 === strpos( $value, self::CIPHER_PREFIX_SODIUM ) || 0 === strpos( $value, self::CIPHER_PREFIX_PLAIN ); } /** * Derives the encryption key from the site salts. * * @return string A raw 32 byte key. */ private function get_key(): string { return sodium_crypto_generichash( wp_salt( 'auth' ), '', SODIUM_CRYPTO_SECRETBOX_KEYBYTES ); } /** * Whether libsodium is usable on this host. * * @return bool True when the functions and constants encrypt() needs are present. */ private function has_sodium(): bool { return function_exists( 'sodium_crypto_secretbox' ) && function_exists( 'sodium_crypto_secretbox_open' ) && function_exists( 'sodium_crypto_generichash' ) && defined( 'SODIUM_CRYPTO_SECRETBOX_NONCEBYTES' ) && defined( 'SODIUM_CRYPTO_SECRETBOX_KEYBYTES' ); } /** * Resolves the SMTP port, falling back to the default when the stored value is unusable. * * @return int The port to connect on. */ private function get_port(): int { $port = (int) ( $this->settings['smtp_port'] ?? 0 ); return ( 0 < $port && 65536 > $port ) ? $port : self::DEFAULT_PORT; } /** * Resolves the encryption method, falling back to TLS for any unrecognised value. * * @return string One of the ENCRYPTION_* values. */ private function get_encryption(): string { $encryption = (string) ( $this->settings['smtp_encryption'] ?? self::ENCRYPTION_TLS ); $accepted = [ self::ENCRYPTION_NONE, self::ENCRYPTION_SSL, self::ENCRYPTION_TLS ]; return in_array( $encryption, $accepted, true ) ? $encryption : self::ENCRYPTION_TLS; } /** * Resolves how long PHPMailer may wait on the mail server. * * @return int The timeout in seconds. */ private function get_timeout(): int { $timeout = $this->testing ? self::TEST_TIMEOUT_SECONDS : self::SEND_TIMEOUT_SECONDS; /** * Filters how long PHPMailer waits for the connection and for each reply. * * A mail server that is genuinely slow to answer, rather than unreachable, can be * given more room here without going back to PHPMailer's own five minute default. * * @param int $timeout The timeout in seconds. * @param bool $testing Whether this is the test send rather than ordinary mail. */ $timeout = (int) apply_filters( 'adminease_smtp_timeout', $timeout, $this->testing ); return 0 < $timeout ? $timeout : self::SEND_TIMEOUT_SECONDS; } /** * Whether to log in to the mail server. * * The switch is on before it has ever been saved, so a missing key has to read as on * here too. Reading it as off would let a configuration holding nothing but a host * count as complete and send every email unauthenticated, with the screen showing the * opposite of what was happening. * * @return bool True when authentication is on. */ private function is_auth_enabled(): bool { if( !array_key_exists( 'smtp_auth', $this->settings ) ) { return true; } return !empty( $this->settings['smtp_auth'] ); } /** * Whether an address is the wordpress@yoursite placeholder WordPress invents when * nothing else has set a sender. * * @param string $from_email The address to test. * * @return bool True when the address is WordPress's own default. */ private function is_default_from_email( string $from_email ): bool { $sitename = strtolower( (string) wp_parse_url( network_home_url(), PHP_URL_HOST ) ); if( 'www.' === substr( $sitename, 0, 4 ) ) { $sitename = substr( $sitename, 4 ); } return strtolower( $from_email ) === 'wordpress@' . $sitename; } /** * Builds the help text under the password field. * * @return string The field description. */ private function get_password_field_description(): string { if( defined( 'ADMINEASE_SMTP_PASS' ) && '' !== (string) ADMINEASE_SMTP_PASS ) { return __( 'The password is being read from the ADMINEASE_SMTP_PASS constant in your wp-config.php file, so anything typed here is ignored.', 'adminease' ); } if( $this->has_unreadable_password() ) { return __( 'A password is saved but it can no longer be read, which happens when the security keys in your wp-config.php file are changed. Type the password in again to fix it.', 'adminease' ); } if( $this->has_stored_password() ) { return __( 'A password is already saved. Leave this empty to keep it, or type a new one to replace it. The saved value is never shown here.', 'adminease' ); } return __( 'Gmail and other providers with two factor authentication need an App Password rather than your account password. The value is encrypted before it is stored and is never shown here again.', 'adminease' ); } /** * Whether there is enough saved configuration to hand mail to the SMTP server. * * @return bool True when the connection can be attempted. */ private function is_configured(): bool { $missing = $this->get_missing_requirements(); return empty( $missing ); } /** * Lists the settings still needed before mail can be sent through the server. * * @return array Translated field labels. */ private function get_missing_requirements(): array { $missing = []; if( '' === trim( (string) ( $this->settings['smtp_host'] ?? '' ) ) ) { $missing[] = __( 'SMTP host', 'adminease' ); } if( $this->is_auth_enabled() ) { if( '' === trim( (string) ( $this->settings['smtp_username'] ?? '' ) ) ) { $missing[] = __( 'SMTP username', 'adminease' ); } if( '' === $this->get_password() ) { $missing[] = __( 'SMTP password', 'adminease' ); } } return $missing; } /** * Builds the warnings shown under the main toggle. * * Several things can be wrong without anything failing loudly: the settings are * incomplete so the feature is standing aside, the stored password can no longer be * read, the port and the encryption contradict each other, the From address is not * the mailbox being logged into, or a second mail plugin is configuring PHPMailer as * well. All of them are stated rather than left to be noticed. * * @return string The field description, or an empty string when there is nothing to report. */ private function get_status_notice(): string { $notices = []; $missing = $this->get_missing_requirements(); $enabled = !empty( $this->settings['smtp_enabled'] ); if( $enabled && !empty( $missing ) ) { $notices[] = sprintf( /* translators: %s: comma separated list of setting names. */ esc_html__( 'Not sending through SMTP yet, because %s still needs filling in. Until then your email keeps going out the way it always has, so nothing is broken while you finish setting this up.', 'adminease' ), implode( ', ', array_map( 'esc_html', $missing ) ) ); } if( $enabled && $this->has_unreadable_password() ) { $notices[] = esc_html__( 'The saved SMTP password can no longer be read. This happens when the security keys in your wp-config.php file are changed, and there is no way to recover the old value. Type the password in again and save.', 'adminease' ); } $notices = array_merge( $notices, $this->get_configuration_warnings() ); $conflicts = $this->get_conflicting_mailers(); if( !empty( $conflicts ) ) { $notices[] = sprintf( /* translators: %1$s: comma separated list of active mail plugin names. */ esc_html__( '%1$s is also active and configures outgoing mail as well. While both are switched on your email is sent with the settings from %1$s and not the ones on this page, so sending can fail with an authentication error even when everything here is filled in correctly. Switch %1$s off, or switch this feature off, so that only one of them handles your email.', 'adminease' ), implode( ', ', array_map( 'esc_html', $conflicts ) ) ); } $html = ''; foreach( $notices as $notice ) { $html .= '' . $notice . ''; } return $html; } /** * Warnings about a saved configuration that will connect but not deliver. * * Only the two port and encryption crossings that are always wrong are reported. * Anything other than 587 and 465 is left alone, because providers do legitimately * use other ports, 2525 among them. * * @return array Escaped warning sentences. */ private function get_configuration_warnings(): array { if( empty( $this->settings['smtp_enabled'] ) ) { return []; } $warnings = []; $encryption = $this->get_encryption(); $port = $this->get_port(); if( self::ENCRYPTION_SSL === $encryption && self::PORT_TLS === $port ) { $warnings[] = sprintf( /* translators: 1: the TLS port, 587. 2: the SSL port, 465. */ esc_html__( 'SSL is selected together with port %1$d. That port expects TLS, and SSL on it usually hangs until the connection gives up rather than failing outright. Either switch the encryption to TLS or change the port to %2$d.', 'adminease' ), self::PORT_TLS, self::PORT_SSL ); } if( self::ENCRYPTION_TLS === $encryption && self::PORT_SSL === $port ) { $warnings[] = sprintf( /* translators: 1: the SSL port, 465. 2: the TLS port, 587. */ esc_html__( 'TLS is selected together with port %1$d. That port expects SSL. Either switch the encryption to SSL or change the port to %2$d.', 'adminease' ), self::PORT_SSL, self::PORT_TLS ); } $from_email = trim( (string) ( $this->settings['smtp_from_email'] ?? '' ) ); $username = trim( (string) ( $this->settings['smtp_username'] ?? '' ) ); if( $this->is_auth_enabled() && is_email( $from_email ) && is_email( $username ) && 0 !== strcasecmp( $from_email, $username ) ) { $warnings[] = esc_html__( 'Your From address is not the mailbox you are logging in as. Most providers reject mail sent that way, or quietly replace the address with the mailbox, so a test can pass while real email still fails. Use the login mailbox as the From address unless your provider tells you it allows otherwise.', 'adminease' ); } return $warnings; } /** * Lists the active plugins known to configure PHPMailer. * * @return array Plugin display names. */ private function get_conflicting_mailers(): array { $active = (array) get_option( 'active_plugins', [] ); if( is_multisite() ) { $active = array_merge( $active, array_keys( (array) get_site_option( 'active_sitewide_plugins', [] ) ) ); } $found = []; foreach( self::KNOWN_MAILER_PLUGINS as $basename => $label ) { if( in_array( $basename, $active, true ) ) { $found[] = $label; } } return array_values( array_unique( $found ) ); } }