| @@ -1,8 +1,11 @@ | ||
| 1 | 1 | <?php |
| 2 | 2 | |
| 3 | 3 | namespace FluentBoards\App\Services\Libs; |
| 4 | 4 | |
| 5 | +use Throwable; | |
| 6 | +use WP_Error; | |
| 7 | + | |
| 5 | 8 | class Mailer |
| 6 | 9 | { |
| 7 | 10 | private $subject = ''; |
| 8 | 11 | |
| @@ -106,5 +109,53 @@ | ||
| 106 | 109 | } |
| 107 | 110 | |
| 108 | 111 | return wp_mail($this->to, $this->subject, $this->body, $headers); |
| 109 | 112 | } |
| 113 | + | |
| 114 | + /** Send a notification with result reporting, retaining the generic send() contract. */ | |
| 115 | + public function sendNotification(array $context) | |
| 116 | + { | |
| 117 | + $context['recipient'] = $this->to; | |
| 118 | + try { | |
| 119 | + $sent = $this->send(); | |
| 120 | + } catch (Throwable $e) { | |
| 121 | + self::reportFailure($context, $e); | |
| 122 | + return false; | |
| 123 | + } | |
| 124 | + | |
| 125 | + if (!$sent) { | |
| 126 | + self::reportFailure($context); | |
| 127 | + return false; | |
| 128 | + } | |
| 129 | + | |
| 130 | + // Accepted by wp_mail, not proof of delivery to the recipient's inbox. | |
| 131 | + self::dispatchResult(true, $context); | |
| 132 | + return true; | |
| 133 | + } | |
| 134 | + | |
| 135 | + /** Log only type/ID; email_failed receives context and a WP_Error for diagnostics. */ | |
| 136 | + public static function reportFailure(array $context, ?Throwable $exception = null) | |
| 137 | + { | |
| 138 | + error_log(sprintf( | |
| 139 | + 'FluentBoards email failed: %s #%d.', | |
| 140 | + sanitize_key($context['type'] ?? 'unknown'), | |
| 141 | + absint($context['task_id'] ?? $context['comment_id'] ?? 0) | |
| 142 | + )); | |
| 143 | + $error = new WP_Error('fluent_boards_email_failed', $exception ? $exception->getMessage() : 'wp_mail returned false.'); | |
| 144 | + self::dispatchResult(false, $context, $error); | |
| 145 | + } | |
| 146 | + | |
| 147 | + /** Reporting observers must not interrupt delivery or turn accepted mail into failure. */ | |
| 148 | + private static function dispatchResult(bool $sent, array $context, $error = null) | |
| 149 | + { | |
| 150 | + try { | |
| 151 | + if ($sent) { | |
| 152 | + do_action('fluent_boards/email_sent', $context, $error); | |
| 153 | + } else { | |
| 154 | + do_action('fluent_boards/email_failed', $context, $error); | |
| 155 | + } | |
| 156 | + } catch (Throwable $e) { | |
| 157 | + error_log('FluentBoards email reporting observer failed: ' . ($sent ? 'fluent_boards/email_sent' : 'fluent_boards/email_failed')); | |
| 158 | + } | |
| 159 | + } | |
| 160 | + | |
| 110 | 161 | } |